Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


@ARGV: Command Line Arguments

Perl has a special array called @ARGV . This is the list of arguments passed along with the script name on the command line. Run the following perl script as:

perl myscript.pl hello world how are you
foreach (@ARGV) {
        print "$_\n";
}

Another useful way to get parameters into a program -- this time without user input. The relevance to filehandles is as follows. Run the following perl script as:

perl myscript.pl stuff.txt out.txt

while (<>) {
        print;
}

Short and sweet ? If you don't specify anything in the angle brackets, whatever is in @ARGV is used instead. And after it finishes with the first file, it will carry on with the next and so on. You'll need to remove non-file elements from @ARGV before you use this.

It can be shorter still:

perl myscript.pl stuff.txt out.txt

print while <>;

Read it right to left. It is possible to shorten it even further !

perl myscript.pl stuff.txt out.txt

print <>;

This takes a little explanation. As you know, many things in Perl, including filehandles, can be evaluated in list or scalar context. The result that is returned depends on the context.

If a filehandle is evaluated in scalar context, it returns the first line of whatever file it is reading from. If it is evaluated in list context, it returns a list, the elements of which are the lines of the files it is reading from.

The print function is a list operator, and therefore evaluates everything it is given in list context. As the filehandle is evaluated in list context, it is given a list !

Who said short is sweet? Not my girlfriend, but that's another story. The shortest scripts are not usually the easiest to understand, and not even always the quickest. Aside from knowing what you want to achieve with the program from a functional point of view, you should also know wheter you are coding for maximum performance, easy maintenance or whatever -- because chances those goals may be to some extent mutually exclusive.