Complete Communications Engineering

Perl passes command line arguments to a script using the built-in @ARGV array.  This variable does not need to be declared, it is available automatically to every Perl script.  It behaves the same as any other array variable, so it can be iterated over using foreach, or indexed using brackets.  It is also possible to use built-in array functions such as shift and pop on the @ARGV array.  When using shift and pop, the @ARGV array will be used by default so it doesn’t need to be specified.  (This only works outside of a subroutine, inside a subroutine the argument array, @_, is used by default.)

The following examples show some of the methods that can be used for parsing command line parameters in Perl:

sky.prl

#!/usr/bin/perl

 

my $medium = $ARGV[0];

my $color = $ARGV[1];

print “I painted the sky on $medium using lots of $color.\n”;

 

#EXAMPLE:

#> perl sky.prl paper blue

#> I painted the sky on paper using lots of blue.

#>

forest.prl

#!/usr/bin/perl

 

my ($medium, $color) = @ARGV;

print “I painted a forest on $medium using lots of $color.\n”;

 

#EXAMPLE:

#> perl forest.prl canvas green

#> I painted a forest on canvas using lots of green.

#>

boat.prl

#!/usr/bin/perl

 

my $color = shift;

my $outcome = shift;

print “I painted a $color sailboat.\n”;

if (defined $outcome) {

    print “(And it turned out $outcome.)\n”;

}

 

#EXAMPLE:

#> perl boat.prl yellow

#> I painted a yellow sailboat.

#>

#> perl boat.prl red okay

#> I painted a red sailboat.

#> (And it turned out okay.)

#>

garden.prl

#!/usr/bin/perl

 

print “I planted the following in my garden:\n”;

foreach my $plant (@ARGV) {

    print ”   * $plant\n”;

}

 

#EXAMPLE:

#> perl garden.prl lettuce tomatoes carrots

#> I planted the following in my garden:

#>    * lettuce

#>    * tomatoes

#>    * carrots

#>