如何确定变量Perl中的某些字符

时间:2015-09-19 13:21:28

标签: perl

我试图找出变量$ Fullname1的前三个字符是否包含一个字母" e。"我正在使用的代码是:

if ((substr($Fullname1, 0, 3)) eq 'e'){ print "The first three letters contain an e.\n"; }else { print "The first three letters do not contain an e.\n";}

它似乎无法正常工作。这是正确的方法吗?

3 个答案:

答案 0 :(得分:4)

人们往往忘记了良好的旧 index STR,SUBSTR The index function searches for one string within another, but without the wildcard-like behavior of a full regular-expression pattern match. 功能。

if ( index(substr($Fullname1, 0, 3), 'e') != -1){

因此,这是对这一特定问题的直接解决方案(对于极高的音量,它也快一点,但对于不会产生影响的正常应用程序):

err

答案 1 :(得分:3)

您的原始代码

if ((substr($Fullname1, 0, 3)) eq 'e')

将由3个字符(或更少,如果$Fullname1短于3个字符)组成的字符串与单个字符'e'进行比较,该字符始终失败。

此:

if ( substr( $FullName1, 0, 3 ) =~ /e/ )

生成前3个(或更少)字符的字符串,然后应用正则表达式/e/,它匹配字符串任何位置的单个字母e

查看man perlre了解详情。

答案 2 :(得分:0)

我建议您使用正则表达式来检查变量是否包含零个,一个或两个字符,后跟e。喜欢这个

if ( $Fullname1 =~ /\A.{0,2}e/s ) {

    print "The first three letters contain an e.\n";
}
else {

    print "The first three letters do not contain an e.\n";
}