Perl Script Command Line Parameters/Options

How to print all command line parameters?

Use the @ARGV array, which contains by design all command line parameters. It starts with 0, and ends at $#ARGV

This is the simplest way to use command line parameters in your perl script but, there are other methods.

How to support command line options in a perl script

Getopt::Std

The getopt function expects each switch to have a value (e.g. -n=1) and won't set any values if the switch doesn't have an argument (e.g -n). Its first argument is a string that denotes which switches it expects. Its second argument is a reference to a hash in which it will set the keys and values.

Sample Code Output
#!/usr/bin/perl # getopts-std.pl
use Getopt::Std;

getopts('abc:', \ my %opts );
print <<"HERE"; The value of a $opts{a} b $opts{b} c $opts{c}
HERE
$ perl getopts-std.pl -c foo -a
The value of
a 1
b
c foo

Sample CodeExplanation
getopt('abc'); -a, -b & -c take arguments. Sets $opt_a, $opt_b, $opt_c as a side effect.
getopt('abc', \%opts); -a, -b & -c take arguments. Values in %opts ($otps{a}, $opts{b}, $opts{c})
getopts('def:'); -d & -e are boolean flags, -f takes an argument
Sets $opt_d, $opt_e, $opt_f as a side effect.
getopts('def:', \%opts); Options as above. Values in %opts

--help and --version

getopts() supports --help and --version arguments. If main::HELP_MESSAGE() and/or main::VERSION_MESSAGE() are defined, they are called. In the example below, both are redirected to the usage() function.

sub HELP_MESSAGE { usage(); }
sub VERSION_MESSAGE { usage(); }

Getopt::Long

Sample Code Output
#!/usr/bin/perl
# getopts-long.pl
use Getopt::Long;

my $result = GetOptions( 'debug|d' => \ my $debug, 'verbose|v' => \ my $verbose, );

print <<"HERE";
The value of debug $debug
verbose $verbose
HERE
$ perl getopts-long.pl -verbose
The value of
debug
verbose 1
$ perl getopts-long.pl -v
The value of
debug
verbose 1
$ perl getopts-long.pl -v -d
The value of
debug 1
verbose 1
$ perl getopts-long.pl -v -debug
The value of
debug 1
verbose 1
$ perl getopts-long.pl -v --debug
The value of
debug 1
verbose 1

Links