2

我有两段代码。第一个是我想要的。但是为什么第二个给我1和0(我的英语是正确的,还是“1和0”)而不是“johnchrismandy”。


foreach (@data) {
    print ;
}
//output
john
chris
mandy


foreach  (@data) {
    print chomp ;
}
//output
110

UPDATE:: Thank you guys, I understand it more now. But I don't understand the last part of the doc.

=> You can actually chomp anything that's an lvalue, including an assignment: chomp($cwd = pwd);

4

4 回答 4

6

这是记录在案的行为:“它返回从所有参数中删除的字符总数。” 你要

for (@data) {
   chomp;
   print "$_\n";
}

请注意,它$_是元素的别名@data,因此@data也被修改了。如果你不希望这种情况发生。

for (@data) {
   my $item = $_;
   chomp($item);
   print "$item\n";
}

关于文档的最后一行:

my $item = $_;作为左值返回$item(适合赋值左侧的值)。像这样,

my $item = $_;
chomp($item);

可以写成

chomp( my $item = $_ );
于 2012-09-02T19:07:24.800 回答
1

这是因为您正在打印函数的返回值,chomp这是从其所有参数中删除的字符总数

于 2012-09-02T19:06:27.110 回答
1

chomp返回删除的字符总数。

\n所以它会打印它已经删除了多少。

请按以下方式进行:

foreach  (@data) {
    chomp($_);
    print $_;
}
于 2012-09-02T19:06:57.413 回答
0

正如其他人所说, chomp 返回删除的字符数。在我的特定实例中(单行 perl 替换文件语句中带有 eval 修饰符的正则表达式),我需要在单个语句中获取 chomped 值,而无需单独的打印语句。我终于找到了一个可行的解决方案 - 将 chomp 命令包装在 if 语句中。

从...开始:

$in = "I have COMMITS commits in my log";
$in =~ s/COMMITS/`git log | grep -i '^commit' | wc -l`/e;
print $in;

这将返回:

I have 256
 commits in my log

太好了,我需要大嚼这个,所以我尝试:

$in = "I have COMMITS commits in my log";
$in =~ s/COMMITS/chomp `git log | grep -i '^commit' | wc -l`/e;
print $in;

但这会引发错误:

Can't modify quoted execution (``, qx) in chomp at ./script line 4, near "`git log | grep -i '^commit' | wc -l`}"
Execution of ./script aborted due to compilation errors.

是的,所以我需要将输出分配给本地 var 并 chomp 它:

$in = "I have COMMITS commits in my log";
$in =~ s/COMMITS/chomp (my $VAR = `git log | grep -i '^commit' | wc -l`)/e;
print $in;

但正如我们所说, chomp 返回删除的字符数:

I have 1 commits in my log

然后我发现我可以将它包装在一个 if 语句中并让它返回结果,chomped:

$in = "I have COMMITS commits in my log";
$in =~ s/COMMITS/if (chomp (my $VAR = `git log | grep -i '^commit' | wc -l`)) { $VAR }/e;
print $in;

最后,我在一个语句中得到了命令结果,chomped:

I have 256 commits in my log
于 2013-04-01T21:24:01.183 回答