welcome
2015_newbie
In the case you are trying to learn new things, cosider the below, somehow long, oneliner: you'll find many things to learn about the power of Perl commandline
see perlrun. The oneliner search for occurences of lines in first file given as arguments in all other files.
Just for a matter of taste i've changed 'police' for 'pretty woman' in your example files..
perl -lne '%ln;BEGIN{open $f,shift;map{chomp;$ln{$_}++}<$f>}print qq($
+ARGV line\t$.\t[$_]) if exists $ln{$_};close ARGV if eof'
dog.txt cat.txt other.txt
cat.txt line 2 [pretty woman]
other.txt line 1 [pretty woman]
In details:
perl -lne execute the code 'cause
-e,
-l does autochomp on lines when there is also
-l or -n,
-n assumes a
while loop reading every file passed as arguments. Again see
perlrun
In the oneliner content we have:
%ln that put that lines hash into namespace. Is important have it before the following
BEGIN
block. The
BEGIN block executes as soon as possible: so it
shift @ARGV (see
shift to know why) privating the
-n switch of his first argument. That shifted arg is opened and then the list returned by
<$f> (the diamond operator return all lines in list context!) is elaborated by
map. We are in a
BEGIN block so (i suppose) is too early for the
-l switch to do his autochomp so in the block we
chomp and autoincrement the value of the key
$_ (is the current line feeded by
<$f>) of the hash
%ln.
Now we are in the main body of the oneliner where
-ln are in effect; we print the current filename (
$ARGV when using the diamond operator
<> see
perlvar) the line num
$. (again
perlvar) and the current line
$_ but we print only if exists the corresponding hash entry
$ln{$_}
close ARGV if eof close the special filhandle
ARGV(se
perlvar) if
eof is reached: this is important because
$. does not reset in case of implicit close of a filehandle, as in our case. Remove that part to see
$. constantly increasing for every file opened.
Have fun and happy new year (maybe reading
Perl White Magic - Special Variables and Command Line Switches)
L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.