[英]chomp in perl not working as expected
我在Perl中发现了一个奇怪的chomp行为,我无法理解chomp为什么会像这样工作。
以下行无法按预期工作
if ( chomp($str1) eq chomp($str2) )
但是,以下工作正常
chomp $str1;
chomp $str2;
if ( $str1 eq $str2 )
你能否对chomp的这种行为有所了解?
chomp
修改了它的参数。 它不会返回修改后的参数。 事实上,第二个例子就是你应该如何使用它。
编辑 : perldoc -f chomp
说:
chomp This safer version of "chop" removes any trailing string that
corresponds to the current value of $/ (also known as
$INPUT_RECORD_SEPARATOR in the "English" module). It returns
the total number of characters removed from all its arguments.
chomp
返回已删除的字符数,而不是已被删除的字符串。
我喜欢名字chomp()它的声音告诉你它的作用。 正如@ruakh所提到的,它需要一个或多个参数,所以你可以说:
chomp($str1,$str2);
if ( $str1 eq $str2 ) ...
您也可以将其设置为一个字符串数组,就像您一次读取整个文件所获得的那样,例如:
chomp(@lines);
通常,您可以使用s,$/$,,r
regex作为非破坏性的chomp。 它从$_
的末尾删除记录分隔符$/
或使用=~
提供的字符串,并返回结果而不修改任何内容。 您的示例如下所示:
if ( $str1 =~ s,$/$,,r eq $str2 =~ s,$/$,,r )
更正式的正则表达式应该是s,\\Q$/\\E$,,r
,所以$/
不被视为正则表达式。 在段落模式中,正则表达式需要是s,\\n*$,,r
。 在slurp或固定记录模式下,根本不需要正则表达式(chomp什么都不做)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.