home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


6.2 Input from the Diamond Operator

Another way to read input is with the diamond operator: <> . This works like <STDIN> in that it returns a single line in a scalar context ( undef if all the lines have been read) or all remaining lines if used in a list context. However, unlike <STDIN> , the diamond operator gets its data from the file or files specified on the command line that invoked the Perl program. For example, you have a program named kitty , consisting of

#!/usr/bin/perl
while (<>) {
    print $_;
}

and you invoke kitty with

kitty file1 file2 file3

then the diamond operator reads each line of file1 followed by each line of file2 and file3 in turn, returning undef only when all of the lines have been read. As you can see, kitty works a little like the UNIX command cat , sending all the lines of the named files to standard output in sequence. If, like cat , you don't specify any filenames on the command line, the diamond operator reads from standard input automatically.

Technically, the diamond operator isn't looking literally at the command-line arguments; it works from the @ARGV array. This array is a special array initialized by the Perl interpreter to the command-line arguments. Each command-line argument goes into a separate element of the @ARGV array. You can interpret this list any way you want.[ 2 ] You can even set this array within your program and have the diamond operator work on that new list rather than the command-line arguments, like so:

@ARGV = ("aaa","bbb","ccc");
while (<>) { # process files aaa, bbb, and ccc
    print "this line is: $_";
}

[2] The standard Perl distribution contains modules for getopt -like parsing of the command-line arguments of a Perl program. See Programming Perl or perlmodlib (1) for more information on the library.

In Chapter 10, Filehandles and File Tests , we'll see how to open and close specific filenames at specific times, but this technique has been used for some of our quick-and-dirty programs.