1.8.1 @ARGV: The Special List Variable
Suppose we want to write a program called myargv.pl that takes any number of command line arguments and writes them out to the standard output filehandle STDOUT with some comments. A call to the program in an Unix environment looks like:
%myargv.pl x y z abc uvw
Here x, y, and z are command line arguments to the program myargv.pl. When we specify a list of command line arguments, the list is not included in parentheses like a regular function call. Also, the arguments are not comma-separated. They are separated simply by one or more spaces.
The program writes out the arguments with some additional comments. The output looks like:
Command line argument #0 = x
Command line argument #1 = y
Command line argument #2 = z
Command line argument #3 = abc
Command line argument #4 = uvw
All command line arguments printed.
This program can take any number of arguments. A program is given below.
Program 1.12
#!/usr/bin/perl
#file myargv.pl
#Prints the arguments given in command line, one per line with
#some additional comments
use strict;
my $i;
for ($i=0; $i <= $#ARGV; $i++){
print "Command line argument #$i = $ARGV[$i]\n";
if ($i == $#ARGV) {
print "All command line arguments printed.\n";
}
This program uses a variable called $i that acts as an index to the @ARGV special list variable that is automatically defined inside the program. The special list variable @ARGV contains all the arguments with which the program has been called. Since @ARGV is a special variable, it must not be declared with my.
The body of the program has a for loop. This loop has an index variable that starts with a count of zero and goes up to $#ARGV. If we have a list variable whose name starts with @, we can obtain the index of the last element in it by writing $# in front of it instead of @. The $ sign tells us that it is a scalar. So, the for loop is executed for every element in the @ARGV list. In other words, the body of the for loop is executed once for every command line argument to the myargv.pl command.
The body of the loop prints the element of @ARGV corresponding to the current value of the loop index. If it is the last element of the argument list, it prints a newline, otherwise, it prints an empty space character.
