Monday, September 13, 2010

Command line arg in perl

In perl, command-line arguments are stored in the array named @ARGV.

$ARGV[0] contains the first argument, $ARGV[1] contains the second argument, etc. So if you're just looking for one command line argument you can test for  $ARGV[0], and if you're looking for two you can test for  $ARGV[1], and so on. (Or you can use a loop, as shown below.)
$#ARGV is the subscript of the last element of the @ARGV array, so the number of arguments on the command line is $#ARGV + 1.

Here's a simple Perl program that prints the number of command-line arguments it's given, and the values of the arguments:
$numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments:\n";

foreach $argnum (0 .. $#ARGV) {

print "$ARGV[$argnum]\n";

}
When a program is executed, the command line arguments go into a special array called @ARGV.And $_
is the special variable which is used as current element of @ARGV.
Eg.

foreach (@ARGV) {
print "$_\n";
}

This program prints the command line arguments on the screen.


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;
}
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 <>;

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 exclu

No comments:

Post a Comment