【问题标题】:Chomp changes my string to 1Chomp 将我的字符串更改为 1
【发布时间】:2013-02-18 11:57:10
【问题描述】:

在我的代码中,我分配了一个变量 disc 以等于我的 linux 系统上命令 disc 的结果。这将输出字符串 RESEARCH

my $disc = `disc`;
print "$disc\n";
$disc = chomp($disc);
print "$disc\n";

但是,当我使用 chomp 从字符串中去除换行符时,它会将字符串更改为 1。这是输出

RESEARCH

1

发生了什么事?

【问题讨论】:

    标签: perl chomp


    【解决方案1】:

    来自perldoc -f chomp

    chomp VARIABLE
    chomp( LIST )
    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. 
    

    正确的用法是简单地提供一个将在适当位置更改的变量或列表。返回值,也就是你使用的,是它“chomped”它的参数列表的次数。例如

    chomp $disc;
    

    甚至:

    chomp(my $disc = `disc`);
    

    例如,您可以 chomp 整个数组或列表,例如:

    my @file = <$fh>;          # read a whole file
    my $count = chomp(@file);  # counts how many lines were chomped
    

    当然,对于单个标量参数,chomp 返回值只能是 1 或 0。

    【讨论】:

      【解决方案2】:

      避免将 chomp 结果分配给您的变量:

      $disc = chomp($disc);
      

      使用:

      chomp($disc);
      

      这是因为 chomp 修改了给定的字符串并返回从其所有参数中删除的字符总数

      【讨论】:

        【解决方案3】:

        只需使用chomp $disc,不要做作,因为chomp 返回删除的字符数。

        【讨论】:

        • chomp $disc 也返回 1
        • @moadeep:是的,当然,它返回删除的字符数。只需使用chomp $disc;
        猜你喜欢
        • 1970-01-01
        • 2021-04-06
        • 2022-07-20
        • 1970-01-01
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多