繁体   English   中英

chomp给我1和0

[英]chomp giving me 1's and 0's

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


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

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

更新::谢谢你们,我现在更了解它。 但我不明白文档的最后部分。

=>你实际上可以选择任何左值的东西,包括一个赋值:chomp($ cwd = pwd);

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

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

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

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

关于文档的最后一行:

my $item = $_; eft-hand side of an assignment). 返回$item作为一个左值(适于分配的 EFT-右手侧的值)。 因此,

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

可写成

chomp( my $item = $_ );

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

chomp返回删除的字符总数。

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

通过以下方式进行:

foreach  (@data) {
    chomp($_);
    print $_;
}

正如其他人所说,chomp返回删除的字符数。 在我的特定实例中(在一行perl replace-in-file语句中使用eval修饰符的正则表达式),我需要在单个语句中获取chomped值而不需要单独的print语句。 我终于找到了一个有效的解决方案 - 将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并将其扼杀:

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM