from
http://alvinalexander.com/perl/perl-command-line-arguments-read-args
How to read Perl command-line arguments
Perl FAQ: How do I read command-line arguments in Perl?
Note: If you want to handle simple Perl command line arguments, such as filenames and strings, this tutorial shows how to do that. If you want to handle command-line options (flags) in your Perl scripts (like "-h" or "--help"), this new Perl getopts command line options/flags tutorial is what you need.
Perl command line args and the @ARGV array
With Perl, command-line arguments are stored in a special array named @ARGV
. So you just need to read from that array to access your script's command-line arguments.
ARGV array elements: In the ARGV array, $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 also test for $ARGV[1], and so on.
ARGV array size: The variable $#ARGV
is the subscript of the last element of the @ARGV
array, and because the array is zero-based, the number of arguments given on the command line is $#ARGV + 1
.
Example 1: A typical Perl command line args example
A typical Perl script that uses command-line arguments will (a) test for the number of command line arguments the user supplied and then (b) attempt to use them. Here's a simple Perl script named name.pl that expects to see two command-line arguments, a person's first name and last name, and then prints them:
#!/usr/bin/perl -w # (1) quit unless we have the correct number of command-line args $num_args = $#ARGV + 1; if ($num_args != 2) { print " Usage: name.pl first_name last_name "; exit; } # (2) we got two command line args, so assume they are the # first name and last name $first_name=$ARGV[0]; $last_name=$ARGV[1]; print "Hello, $first_name $last_name ";
This is fairly straightforward, where adding 1 to $#ARGV strikes me as the only really unusual thing.
To test this script on a Unix/Linux system, just create a file named name.pl, then issue this command to make the script executable:
chmod +x name.pl
Then run the script like this:
./name.pl Alvin Alexander
Or, if you want to see the usage statement, run the script without any command line arguments, like this:
./name.pl