[英]chomp in perl not working as expected
I found a strange behavior of chomp in Perl and I am unable to comprehend why is chomp is working like this. 我在Perl中发现了一个奇怪的chomp行为,我无法理解chomp为什么会像这样工作。
The following line does not work as expected 以下行无法按预期工作
if ( chomp($str1) eq chomp($str2) )
But, the following works fine 但是,以下工作正常
chomp $str1;
chomp $str2;
if ( $str1 eq $str2 )
Can you please give some insight in this behavior of chomp? 你能否对chomp的这种行为有所了解?
chomp
modifies its argument. chomp
修改了它的参数。 It does not return a modified argument. 它不会返回修改后的参数。 The second example is, in fact, how you're supposed to use it.
事实上,第二个例子就是你应该如何使用它。
edit : perldoc -f chomp
says: 编辑 :
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
返回已删除的字符数,而不是已被删除的字符串。
I like the name chomp() it's sound tells you what it does. 我喜欢名字chomp()它的声音告诉你它的作用。 As @ruakh mentions it takes one or more arguments, so you can say:
正如@ruakh所提到的,它需要一个或多个参数,所以你可以说:
chomp($str1,$str2);
if ( $str1 eq $str2 ) ...
You can also hand it an array of strings, like what you would get from reading a whole file at once, eg: 您也可以将其设置为一个字符串数组,就像您一次读取整个文件所获得的那样,例如:
chomp(@lines);
Generally, you can use s,$/$,,r
regex as a non-destructive chomp. 通常,您可以使用
s,$/$,,r
regex作为非破坏性的chomp。 It removes record separator $/
from the end of $_
or the string provided using =~
, and returns the result without modifying anything. 它从
$_
的末尾删除记录分隔符$/
或使用=~
提供的字符串,并返回结果而不修改任何内容。 Your example would look like this: 您的示例如下所示:
if ( $str1 =~ s,$/$,,r eq $str2 =~ s,$/$,,r )
More formally the regex should be s,\\Q$/\\E$,,r
, so $/
is not treated as regex. 更正式的正则表达式应该是
s,\\Q$/\\E$,,r
,所以$/
不被视为正则表达式。 In paragraph mode the regex would need to be s,\\n*$,,r
. 在段落模式中,正则表达式需要是
s,\\n*$,,r
。 In slurp or fixed record mode the regex is not needed at all (chomp does nothing). 在slurp或固定记录模式下,根本不需要正则表达式(chomp什么都不做)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.