解释此perl代码,该代码在2个文件中显示公共行 [英] Explain this perl code which displays common lines in 2 files

查看:73
本文介绍了解释此perl代码,该代码在2个文件中显示公共行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个文件共有一个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 @ARGV1.对于每一行,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 @ARGV0.因此,如果一行位于文件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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆