Perl Argv -- Retrieving Command-Line Arguments in Perl

In Perl, command-line program arguments are available via the @ARGV array.

Note that the arguments are placed into @ARGV without regard to their meaning; Perl simply splits on space when populating @ARGV.

For example, let's type:

perl perltest.pl -a test




Where perltest.pl contains this code:

use strict; 
use warnings; 

sub main
{
    foreach my $arg(@ARGV) {
        print "$arg\n";
    }
}

main();




The output from the program is:

-a
test




You can see that Perl doesn't care which arguments are flags and which values. All space-separated strings are simply placed in @ARGV.



More Intelligent Command-Line Option Processing Using Getopts



If you want to retrieve command-line arguments in a way that understands the difference between a flag and a value, use getopts (Note: there's also a function called getopt which is somewhat simpler but less useful; don't leave the 's' off getopts or your program will not work and you won't know why).

Here's an example.

use strict; 
use warnings; 

use Getopt::Std;

sub main
{
    my %opts;

    # Expect three flags, -a, -b and -c.
    # Only -b can take an argument
    # (Hence the : after b).
    getopts('ab:c', %opts);
    
    use Data::Dumper;
    print Dumper(%opts);
}

main();




We type:

perl perltest.pl -a -b hello -c -d




Program output (note, the program warns about -d because we didn't tell getopts about it.

Unknown option: d
$VAR1 = {
          'c' => 1,
          'a' => 1,
          'b' => 'hello'
        };




Above we have a program that takes up to three flags, -a, -b and -c. The colon : after 'b' in the argument to getopts says that the -b flag takes an argument, while the other two flags are boolean; they're either supplied by the user or not.

The flags are inserted into the hash that we pass as a reference to getopts

Perl Command-Line Processing: A Full Example



Let's take a look at a complete example using getopts. The following program expects up to four arguments, two of which are flags and the other two expect arguments.

use strict; 
use warnings; 

use Getopt::Std;

sub main
{
    my %opts;
    
    # Note: colons after a and b, but
    # not after c or d.
    # -a and -b expect arguments.
    getopts('a:b:cd', %opts);
    
    if($opts{c}) {
        print "Got -c flag\n";
    }
    
    if($opts{d}) {
        print "Got -d flag\n";
    }
    
    if($opts{a}) {
        print "Value of -a flag: " . $opts{a} . "\n";
    }
    
    if($opts{b}) {
        print "Value of -b flag: " . $opts{b} . "\n";
    }
}

main();





We enter:

perl perltest.pl -a hello -d




The program outputs:

Got -d flag
Value of -a flag: hello