STDIN
as a filehandle
to the operator. But with no filehandle, the diamond operator will also check
to see if any file names were given on the command line. If there were filenames
on the command line, it will read each of the files in turn, first returning
all the lines from the first file, then the lines from the next file, and so
on. When used in a list context, all of the lines from all of the files are
returned. Thus, perl programs which read their input using an empty diamond
operator can be used by either specifying the file or files to be processed on
the command line, or by accepting those lines from the standard input stream.
In the latter case, such programs are sometimes known as filters.
When you're reading multiple files listed on the command line in this way, perl
doesn't automatically reset it's line counter ($.
) when it opens a new
file, but it does change the value of the automatic variable $ARGV
. So
you can store the value of $ARGV
and compare it to the current value to
discover when a new file has been opened. So to print out an identifying line
and
all the lines in
several files, each preceded by its line number, you could use a program like
the following:
while(<>){ if($ARGV ne $lastargv){ $. = 1; print '=' x 10 . " $ARGV " . '=' x 10 . "\n"; $lastargv = $ARGV; } print "$.: $_"; }To inform the program of the files to print, simply include them as arguments on the command line.