Databases Reference
In-Depth Information
print "Pet roll call:\n".
"===========\n".
"cats:\t$Animals{cats}\n".
"dogs:\t$Animals{dogs}\n".
"fish:\t$Animals{fish}\n".
"===========\n".
"Total:\t$Total\n";
Notice that the hash is indicated by a percentage ( % ) symbol and that, like for arrays,
the individual scalar elements are indicated by a dollar symbol. For example, the num-
ber of cats is contained in $Animals{cats} ; it's common to enclose the identifier in single
or double quotes, as in $Animals{'cats'} or $Animals{"cats"} .
Note that array elements are enclosed in square brackets— $AnimalName[1] —whereas
hash elements are enclosed in curly braces— $Animals{'cats'} .
In this example, we've written the hash keys in the program itself. This is called hard-
coding and is not good practice. Any change to the keys requires a change to the pro-
gram. If we don't know the keys, we can still access the elements by first extracting the
keys into an array using the keys keyword. We can then use the elements in this array
to access the hash elements; for example, instead of typing $Animals{"cats"} , we can
write $Animals{ $AnimalName[0] } . This may be hard to read, but think of it this way:
Perl looks inside the braces and finds $AnimalName[0] . This denotes the first element of
the @AnimalName array, which is cats . Perl then plugs cats in where $AnimalName[0] was,
in order to select the proper value from the %AnimalName hash. Using this syntax in a
program, we can do calculations and printouts:
# Extract the keys of the Animals hash into the AnimalName array
my @AnimalName = keys %Animals;
my $Total=
$Animals{$AnimalName[0]}+
$Animals{$AnimalName[1]}+
$Animals{$AnimalName[2]};
print "Pet roll call:\n".
"===========\n".
"$AnimalName[0]:\t$Animals{$AnimalName[0]}\n".
"$AnimalName[1]:\t$Animals{$AnimalName[1]}\n".
"$AnimalName[2]:\t$Animals{$AnimalName[2]}\n".
"===========\n".
"Total:\t$Total\n";
While it's nice to be able to use a single variable to store the data, there's still a lot of
ugly manual referencing going on in the print statement; if we had a hundred types of
animals, we'd need to reference them all individually. If you thought that we don't
really have to do this, you're right! In the next section, we'll look at how loops can help
simplify processing of arrays.
 
Search WWH ::




Custom Search