如何比较Perl中的两个字符串?

PJT*_*PJT 171 perl string-comparison

如何比较Perl中的两个字符串?

我正在学习Perl,我有这个基本问题在StackOverflow上查找了它并且没有找到好答案所以我想我会问.

Sin*_*nür 175

perldoc perlop.使用lt,gt,eq,ne,并cmp酌情进行字符串比较:

eq如果左参数的字符串等于右参数,则二进制返回true.

ne如果左参数的字符串不等于右参数,则二进制返回true.

二进制cmp返回-1,0或1,具体取决于左参数是否是字符串小于,等于或大于右参数.

Binary ~~在其参数之间进行了智能匹配....

lt,le,ge,gtcmp使用由当前区域指定的排序规则(排序)命令,如果一个传统的使用区域(但不是use locale ':not_characters')生效.见perllocale.不要将这些与Unicode混合,只与传统的二进制编码混合使用.标准的Unicode :: Collat​​eUnicode :: Collat​​e :: Locale模块为排序规则问题提供了更强大的解决方案.

  • 再多一点,ne不等于. (9认同)
  • 你可能想提一下$ str1 =〜"$ str2"(不是/ $ str2 /)会检查$ str2是否是$ str1的子字符串. (4认同)
  • @Daniel:=〜"$ str2"和=〜/ $ str2 /(或者只是=〜$ str2)之间没有太大的实际区别; index是正确的工具,但如果由于某种原因需要使用正则表达式,请执行=〜/\Q $ str2\E /. (3认同)

Bra*_*ert 134

有关perldoc perlop更多信息,请参阅

(我正在简化这一点,但是cmp返回一个既是空字符串又是数字零值而不是字符值的值0,以及一个既是字符串'1'又是数值的值1.这些值与您相同总是从Perl中的布尔运算符得到.你应该只使用boolean或numeric操作的返回值,在这种情况下差异并不重要.)

  • 我更喜欢这个答案.简单的简单示例通常对新手更有帮助,而不仅仅是平庸多页文档参考. (7认同)

Cha*_*ens 17

除了SinanÜnür字符串比较运算符的全面列表外,Perl 5.10还增加了智能匹配运算符.

智能匹配运算符根据其类型比较两个项目.请参阅下面的图表了解5.10行为(我相信这种行为在5.10.1中略有变化):

perldoc perlsyn"详细智能匹配":

智能匹配的行为取决于其参数的类型.它总是可交换的,即$a ~~ $b行为相同$b ~~ $a.行为由下表确定:以任一顺序应用的第一行确定匹配行为.

  $a      $b        Type of Match Implied    Matching Code
  ======  =====     =====================    =============
  (overloading trumps everything)

  Code[+] Code[+]   referential equality     $a == $b   
  Any     Code[+]   scalar sub truth         $b?>($a)   

  Hash    Hash      hash keys identical      [sort keys %$a]~~[sort keys %$b]
  Hash    Array     hash slice existence     grep {exists $a?>{$_}} @$b
  Hash    Regex     hash key grep            grep /$b/, keys %$a
  Hash    Any       hash entry existence     exists $a?>{$b}

  Array   Array     arrays are identical[*]
  Array   Regex     array grep               grep /$b/, @$a
  Array   Num       array contains number    grep $_ == $b, @$a 
  Array   Any       array contains string    grep $_ eq $b, @$a 

  Any     undef     undefined                !defined $a
  Any     Regex     pattern match            $a =~ /$b/ 
  Code()  Code()    results are equal        $a?>() eq $b?>()
  Any     Code()    simple closure truth     $b?>() # ignoring $a
  Num     numish[!] numeric equality         $a == $b   
  Any     Str       string equality          $a eq $b   
  Any     Num       numeric equality         $a == $b   

  Any     Any       string equality          $a eq $b   

+ ? this must be a code reference whose prototype (if present) is not ""
(subs with a "" prototype are dealt with by the 'Code()' entry lower down) 
* ? that is, each element matches the element of same index in the other
array. If a circular reference is found, we fall back to referential 
equality.   
! ? either a real number, or a string that looks like a number

当然,"匹配代码"并不代表真正的匹配代码:它只是用于解释预期含义.与grep不同,智能匹配运算符会尽可能短路.

通过重载进行自定义匹配您可以通过重载~~运算符来更改对象的匹配方式.这胜过了通常的智能匹配语义.见overload.


Mat*_*ley 10

print "Matched!\n" if ($str1 eq $str2)
Run Code Online (Sandbox Code Playgroud)

Perl具有单独的字符串比较和数字比较运算符,以帮助松散键入语言.您应该阅读所有不同运营商的perlop.


nob*_*bar 7

这个问题的明显潜台词是:

为什么你不能==用来检查两个字符串是否相同?

Perl没有针对文本与数字的不同数据类型.它们都由"标量"类型表示.换句话说,如果您使用字符串,字符串就是数字.

if ( 4 == "4" ) { print "true"; } else { print "false"; }
true

if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true

print "3"+4
7
Run Code Online (Sandbox Code Playgroud)

由于文本和数字没有被语言区分,我们不能简单地重载==操作符来为两种情况做正确的事情.因此,Perl提供eq了将值作为文本进行比较:

if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false

if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true
Run Code Online (Sandbox Code Playgroud)

简而言之:

  • Perl没有专门用于文本字符串的数据类型
  • 使用==!=将两个操作数作为数字进行比较
  • 使用eqne将两个操作数作为文本进行比较

还有许多其他函数和运算符可用于比较标量值,但知道这两种形式之间的区别是重要的第一步.