Databases Reference
In-Depth Information
Reading in values from the command line
One option is to specify values after the program name on the command line; these
values are called
command-line arguments
and are saved in the special
ARGV
array vari-
able. For example, if we type:
$
./program.pl
Argument_1 Argument_2 Argument_3
$ARGV[0]
will contain
Argument_1
,
$ARGV[1]
would contain
Argument_2
, and
$ARGV[2]
would contain
Argument_3
. The number of arguments entered at the command line is
the same as the number of elements in the
@ARGV
array; you can find this number by
referring to the name of the array—for example,
@ARGV
will be
3
if three arguments are
typed in at the command line.
Example 16-4 modifies our Animals script to read in the number of cats, dogs, and fish
as command-line arguments.
Example 16-4. Reading in numbers from the command line
#!/usr/bin/perl
use strict;
my %Animals;
# If the user hasn't provided the correct number of command-line
# arguments, provide a helpful error message.
if(@ARGV!=3)
{
die("Syntax: $0 [count of cats] [count of dogs] [count of fish]\n");
}
# If the user has provided the command-line arguments, fill in the
# Animals hash with the corresponding values.
%Animals=(
"cats"=>$ARGV[0],
"dogs"=>$ARGV[1],
"fish"=>$ARGV[2]);
# Process the data to calculate the total; code beyond this point is
# identical to our previous example, and doesn't deal with the
# command-line arguments.
my $Total=0;
print "Pet roll call:\n".
"===========\n";
while ((my $Animal, my $Count) = each(%Animals))
{
print "$Animal:\t$Count\n";
$Total+=$Count;
}
print "===========\n".
"Total:\t$Total\n";
If an incorrect number of arguments is provided, the
die
statement prints the message
string between the parentheses and then stops the program. Since the program will run