Chomp将我的字符串更改为1

时间:2013-02-18 11:57:11

标签: perl chomp

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

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

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

RESEARCH

1

发生了什么事?

3 个答案:

答案 0 :(得分:7)

来自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. 

正确的用法是简单地提供一个将被改变的变量或列表。你使用的返回值是它“扼杀”其参数列表的次数。 E.g。

chomp $disc;

甚至:

chomp(my $disc = `disc`);

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

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

当然,使用单个标量参数,chomp返回值只能是1或0.

答案 1 :(得分:2)

只需使用chomp $disc而不做出任何影响,因为chomp会返回删除的字符数。

答案 2 :(得分:1)

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

$disc = chomp($disc);

使用:

chomp($disc);

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

中删除的字符总数