我如何在这个衬里中使用条件?
我有一个包含 3 列的输入文件,我想打印第三列未重复的行。因此,如果我的输入数据如下所示:
0,1,abc
0,2,abc
0,5,xyz
我将打印:
0,1,abc
0,5,xyz
我最初从下面开始,但它没有产生任何输出。我在这行做错了什么?
perl -ne '/^[0-9]+,[0-9]+,(.+)/ && ++$a{$1} && print "$_ $a{$1}\n" if $a{$1}>0'
请注意,我并不是在寻找问题的解决方案,因为我以不同的方式对其进行了编码。但我感兴趣的是为什么上面的行没有达到我的预期,因为它暴露了我对 Perl 理解的差距。
I have an input file with 3 columns, and I wanted to print lines where the 3rd column hasn't been duplicated. so if my input data looks like this:
0,1,abc
0,2,abc
0,5,xyz
I would print:
0,1,abc
0,5,xyz
I initially started with the below, but it didn't produce any output. what am I doing wrong in this line?
perl -ne '/^[0-9]+,[0-9]+,(.+)/ && ++$a{$1} && print "$_ $a{$1}\n" if $a{$1}>0'
please note that I'm not looking for a solution to my problem, as I coded it in a different way. but I am interested in why the above line doesn't do what I expect, as it exposes a gap in my perl understanding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一方面,后缀
if $a{$1} > 0
表达式首先被求值,就像你说的那样,但是
$a{...}
(和$1
)只会在if 内更新
块,因此if
语句永远不会为 true。另一方面,您的正则表达式有双引号字符,但您的示例输入没有。这是一个错字吗?
For one thing, the postfix
if $a{$1} > 0
expression gets evaluated first, as if you saidbut
$a{...}
(and$1
) will only get updated inside theif
block, so theif
statement is never true.For another thing, your regex has double quote characters but your sample input doesn't. Was that a typo?
您发布的内容还包括打印 $a{$1} 的值。
我认为那是为了调试。
我把“\n”去掉了,因为$1中已经有换行了。
如果你想改变它,请在行的开头使用 chomp 。
虽然使用 &&一行很漂亮,我想这会是
尝试在真正的格式化块中编写 Perl 是个好建议。这会
帮助您更好地学习,更轻松地调试。
看看你的台词,很难立即看出
更好的学习方法(在我看来)的真正意图是什么。
对此:
What you posted, had also included printing the value of $a{$1}.
I assume that was for debug.
I took out the "\n" because there is already a line feed in $1.
If you want to change that, use chomp at the beginning of the line.
Although using the && in a single line is nifty, I think it would be
good advice to try and write the perl in a real formatted block. This would
help you learn better, and debug easier.
Looking at your line, it is not immediately easy to see what the true intention of
A better approach for learning ( In my opinion ) would have been something similar
to this: