Databases Reference
In-Depth Information
# 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";
This compact program combines many of the features of Perl you've learned so far.
Loops allow you to process as many data items as required; when you're writing a
program, you generally don't know exactly how many rows of data will be returned by
the database. The example also illustrates the
if
control statement, the
||
logical OR
operator, and an appropriately used array and hash.
You can also see how the program uses scope to limit the visibility of its variables. The
first
while
block defines two variables (
$AnimalName
and
$AnimalCount
) that can be used
only within the loop. The second
while
block defines two more variables within the
while
statement itself; these can be used only within that block. Because these variables
serve a temporary function inside the loop and aren't needed outside it, defining them
within the scope of the block is good coding practice.
In our test for command-line arguments, we print the error message if the user hasn't
provided any command-line arguments (the number of arguments is zero), or if there
aren't an integer number of animal name and count pairs (which we'll know because
there will be a remainder when we divide the number of arguments by two:
@ARGV%2
).
To read in the command-line arguments, we use the
shift
function to pick up one
argument from the list. We expect a name and a count, so we call
shift
twice for each
animal. The
while
loop continues as long as there are additional arguments, so we can
provide data for as many animals as we like.
Let's try the program out:
$
./animals.commandline.types.pl
dogs 7 fish 33 elephants 1 giraffes 3
Pet roll call:
===========
giraffes: 3
cats: 4
elephants: 1
dogs: 7
fish: 33
===========
Total: 48