Приглашаем посетить
Путешествия (otpusk-info.ru)

[Chapter 6] 6.2 Input from the Diamond Operator

PreviousChapter 6
Basic I/O
Next
 

6.2 Input from the Diamond Operator

Another way to read input is with the diamond operator: <>. This operator 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, if you have a program named type.plx, consisting of:

while (<>) {
        print $_;
}

and you invoke type.plx with:

perl type.plx 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, type.plx works a little like the NT command type, sending all the lines of the named files to standard output in sequence. If 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:

[2] The Perl standard distribution contains routines for parsing the command-line arguments of a Perl program. See Programming Perl for more information on the getopt library.

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

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


PreviousHomeNext
6.1 Input from STDINBook Index6.3 Output to STDOUT