Command line arguments with Perl

Posted: 27th December 2013 by Tim in Perl
Tags: , , , , ,

Command line arguments in perl are stored in the $ARGV array, and the number of arguments can be deduced from the size of that array: $#ARGV + 1. One way to access this data is to access the data by index: $ARGV[0] for the first argument for example. Unlike C, the program name is not passed as the first argument.

For example, the following Perl program will print all arguments passed to it:

print "There are " . ($#ARGV + 1) . " arguments:\n";
for (my $i = 0; $i <= $#ARGV; ++$i)
{
    print "  \$ARGV[" . $i . "] = " . $ARGV[$i] . "\n";
}

$ perl <script_name> first second third
There are 3 arguments:
  $ARGV[0] = first
  $ARGV[1] = second
  $ARGV[2] = third