Databases Reference
In-Depth Information
beyond this point only if a correct number of arguments is provided, there's no need
to include an else clause to handle such a case.
Save this script as animals.commandline.pl and run it with command-line arguments:
$ ./animals.commandline.pl 3 7 4
Pet roll call:
===========
cats: 3
dogs: 7
fish: 4
===========
Total: 14
As part of the error message, we've used the $0 variable, which is the command used
to run the script. If, by mistake, you use too many or too few arguments, you get the
helpful error message shown below:
$ ./animals.commandline.pl 3 7 4 1
Syntax: ./animals.commandline.pl [count of cats] [count of dogs] [count of fish]
Here, $0 is replaced by ./animals.commandline.pl .
Notice that we still have the animal names hardcoded in the program; each time we
want to change the list of animals, we need to change the program code. We can instead
change our program to read in both the animal names and counts from the command
line, as shown in Example 16-5:
Example 16-5. Reading in both the animal names and counts from the command line
#!/usr/bin/perl
use strict;
my %Animals;
# If the user hasn't provided a nonzero, even number of command-line
# arguments, provide a helpful error message.
if( (@ARGV==0) || ( (@ARGV%2)!=0) )
{
die("Syntax: $0 [Animal One Name] [Animal One Count] ".
"[Animal Two Name] [Animal Two Count] ...\n");
}
# If the user has provided the command-line arguments, fill in the
# Animals hash with the corresponding values.
while(@ARGV)
{
# Read in an argument and take this as the animal name
my $AnimalName=shift(@ARGV);
# Read in another argument and take this as the count for this animal
my $AnimalCount=shift(@ARGV);
# Add an entry to the Animals hash for this animal name and
# count pair:
$Animals{$AnimalName}=$AnimalCount;
}
 
Search WWH ::




Custom Search