Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this perl code which displays common lines in 2 files

Tags:

How does this perl one-liner display lines that 2 files have in common?

perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2 
like image 516
Kelvin Avatar asked Jul 09 '13 15:07

Kelvin


People also ask

How do I find the common line of two files?

Use comm -12 file1 file2 to get common lines in both files. You may also needs your file to be sorted to comm to work as expected. Or using grep command you need to add -x option to match the whole line as a matching pattern. The F option is telling grep that match pattern as a string not a regex match.


1 Answers

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$/;   } } 

While the first file is being read, scalar @ARGV is 1. For each line, 1 will be appended to the %seen entry.

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).

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.

like image 135
amon Avatar answered Sep 19 '22 20:09

amon