【问题标题】:chomp in perl not working as expectedperl 中的 chomp 无法按预期工作
【发布时间】: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


    【解决方案1】:

    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.
    

    【讨论】:

    • +1。更明确地说:chomp 接受一个或多个参数,必要时修改它们,并“返回从所有参数中删除的字符总数”。 [link]
    • 我一直认为应该有一个rchomp,它的行为符合OP的预期。我觉得chomp( my $input = <> );看起来很别扭,你不是更喜欢my $input = rchomp <>
    • 我讨厌这些修改参数的 C 风格接口。 Text::Chomped 是解决方法。
    • 修改它的最初想法是,您可以使用隐式参数 ($_) 编写您的 perl 脚本,并像 while(<STDIN>) { chomp; next if /begin_pattern/../end_pattern/; s/x/y/; print; } 一样拥有它——这就是 Perl 的来源,从历史上看,这就是人们觉得古怪的大多数事情的根源。不过,我同意它在大多数现代编程中都是可疑的。
    【解决方案2】:

    chomp 返回删除的字符数,而不是已压缩的字符串。

    【讨论】:

      【解决方案3】:

      我喜欢 chomp() 这个名字,它的声音告诉你它做了什么。正如@ruakh 提到的,它需要一个或多个参数,所以你可以说:

      chomp($str1,$str2);
      if ( $str1 eq $str2 ) ...
      

      你也可以给它一个字符串数组,就像一次读取整个文件一样,例如:

      chomp(@lines);
      

      【讨论】:

        【解决方案4】:

        通常,您可以使用s,$/$,,r 正则表达式作为非破坏性的选择。它从$_ 或使用=~ 提供的字符串的末尾删除记录分隔符$/,并在不修改任何内容的情况下返回结果。您的示例如下所示:

        if ( $str1 =~ s,$/$,,r eq $str2 =~ s,$/$,,r )
        

        更正式的正则表达式应该是s,\Q$/\E$,,r,所以$/ 不被视为正则表达式。在段落模式下,正则表达式需要为s,\n*$,,r。在 slurp 或固定记录模式下,根本不需要正则表达式(chomp 什么都不做)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-23
          • 2014-12-09
          • 2016-01-13
          • 2020-09-21
          • 2011-08-17
          • 2012-04-29
          • 2021-08-12
          • 2019-02-04
          相关资源
          最近更新 更多