Databases Reference
In-Depth Information
print "===========\n".
"Total:\t$Total\n";
For each value of
$AnimalName
, the statements between the braces are executed. First,
the
+=
operator is used to increase the value of the $
Total
variable by the count of that
animal, and then the name and count of each animal is printed. Note that we initialized
the value of
$Total
to zero before we start adding values to it.
The
foreach
construct shown here extracts the keys of the
%Animals
hash, but we have
to use the hash together with the key to find each value. The following
while
statement
does the same thing, but in a cleaner way:
while( (my $AnimalName, my $Count) = each(%Animals) )
{
print "$AnimalName:\t$Count\n";
$Total+=$Count;
}
Each time round the loop, the
each
construct assigns the animal name (the key) and
count (the value) to the
$AnimalName
and
$Count
variables. The loop is repeated, and
the statements within the braces are executed until all the items in the hash are ex-
hausted.
Conditional Statements
Sometimes, we want to execute a statement only if something is true, or only if it's false.
The
if
construct allows this:
# Numerical comparison
my $var1=786;
if($var1 < 786)
{
print "The value is less than 786.\n";
}
if($var1 >= 786)
{
print "The value is greater than or equal to 786.\n";
}
if($var1 == 786)
{
print "The value is equal to 786.\n";
}
If we want to compare strings, rather than numbers, we need to use the string com-
parison operators. The important ones are
eq
(equal),
lt
(alphabetically earlier than),
and
gt
(alphabetically later than):