next up previous contents
Next: Printing Up: Basic I/O Previous: The ``diamond'' operator   Contents


The empty diamond operator (<>)

We've already seen that perl often has intelligent defaults when information is omitted, and the diamond operator is one of the best examples of that practice. When you use an empty diamond operator, perl will read its input from the standard input stream, just as if you had specified 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.


next up previous contents
Next: Printing Up: Basic I/O Previous: The ``diamond'' operator   Contents
Phil Spector 2002-10-18