【发布时间】:2012-03-05 11:14:34
【问题描述】:
我在 Perl 中发现了一个奇怪的 chomp 行为,我无法理解为什么 chomp 会这样工作。
以下行没有按预期工作
if ( chomp($str1) eq chomp($str2) )
但是,以下工作正常
chomp $str1;
chomp $str2;
if ( $str1 eq $str2 )
您能否对这种 chomp 行为提供一些见解?
【问题讨论】:
我在 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 接受一个或多个参数,必要时修改它们,并“返回从所有参数中删除的字符总数”。 [link]
rchomp,它的行为符合OP的预期。我觉得chomp( my $input = <> );看起来很别扭,你不是更喜欢my $input = rchomp <>
$_) 编写您的 perl 脚本,并像 while(<STDIN>) { chomp; next if /begin_pattern/../end_pattern/; s/x/y/; print; } 一样拥有它——这就是 Perl 的来源,从历史上看,这就是人们觉得古怪的大多数事情的根源。不过,我同意它在大多数现代编程中都是可疑的。
chomp 返回删除的字符数,而不是已压缩的字符串。
【讨论】:
我喜欢 chomp() 这个名字,它的声音告诉你它做了什么。正如@ruakh 提到的,它需要一个或多个参数,所以你可以说:
chomp($str1,$str2);
if ( $str1 eq $str2 ) ...
你也可以给它一个字符串数组,就像一次读取整个文件一样,例如:
chomp(@lines);
【讨论】:
通常,您可以使用s,$/$,,r 正则表达式作为非破坏性的选择。它从$_ 或使用=~ 提供的字符串的末尾删除记录分隔符$/,并在不修改任何内容的情况下返回结果。您的示例如下所示:
if ( $str1 =~ s,$/$,,r eq $str2 =~ s,$/$,,r )
更正式的正则表达式应该是s,\Q$/\E$,,r,所以$/ 不被视为正则表达式。在段落模式下,正则表达式需要为s,\n*$,,r。在 slurp 或固定记录模式下,根本不需要正则表达式(chomp 什么都不做)。
【讨论】: