解释此perl代码,该代码在2个文件中显示公共行 [英] Explain this perl code which displays common lines in 2 files
问题描述
这两个文件共有一个perl单线显示行吗?
How does this perl one-liner display lines that 2 files have in common?
perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/' file1 file2
推荐答案
-n
命令行选项将代码转换为等同于
The -n
command line option transforms the code to something equivalent to
while ($ARGV = shift @ARGV) {
open ARGV, $ARGV;
LINE: while (defined($_ = <ARGV>)) {
$seen{$_} .= @ARGV;
print $_ if $seen{$_} =~ /10$/;
}
}
在读取第一个文件时,scalar @ARGV
是1
.对于每一行,1
将被附加到%seen
条目.
While the first file is being read, scalar @ARGV
is 1
. For each line, 1
will be appended to the %seen
entry.
在读取第二个文件时,scalar @ARGV
是0
.因此,如果一行位于文件1和文件2中,则该条目将看起来像1110000
(在文件1中为3倍,在文件2中为4倍).
While the second file is being read, scalar @ARGV
is 0
. So if a line was in file 1 and in file2, the entry will look like 1110000
(it was 3× in file1, 4× in file2).
我们只想输出一条公共线.当在file2中首次出现一条公共行时,我们执行此操作,因此$seen{$_}
为1110
.这用正则表达式/10$/
表示:字符串10
必须出现在末尾.
We only want to output common lines exactly one time. We do this when a common line was first seen in file2, so $seen{$_}
is 1110
. This is expressed as the regex /10$/
: The string 10
must appear at the end.
这篇关于解释此perl代码,该代码在2个文件中显示公共行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!