Databases Reference
In-Depth Information
my $AnimalNameOne="cats";
my $AnimalNameTwo="dogs";
my $AnimalNameThree="fish";
my $AnimalCountOne=3;
my $AnimalCountTwo=7;
my $AnimalCountThree=4;
Such scalar variables work well enough for three animals but would be difficult to use
if we were trying to keep track of the hundreds of species in a zoo. A better way to
manage similar values is to store them as a list in a single array variable, with the data
on each animal stored in a numbered element in the array. Example 16-2 rewrites the
script in Example 16-1 accordingly.
Example 16-2. Perl script using array variables
#!/usr/bin/perl
use strict;
my @AnimalName=("cats", "dogs", "fish");
my @AnimalCount=(3, 7, 4);
my $Total=$AnimalCount[0]+$AnimalCount[1]+$AnimalCount[2];
print "Pet roll call:\n".
"===========\n".
"$AnimalName[0]:\t$AnimalCount[0]\n".
"$AnimalName[1]:\t$AnimalCount[1]\n".
"$AnimalName[2]:\t$AnimalCount[2]\n".
"===========\n".
"Total:\t$Total\n";
The @AnimalName array contains three elements with the values cats , dogs , and fish .
Elements in the list are labeled starting from zero, so the first element is element 0 , the
second is element 1 , the third is element 2 , and so on. Array variables are indicated by
the at ( @ ) symbol; the individual elements in the array are scalar variables, so they are
indicated with the dollar ( $ ) symbol. For example, the second element in the
@AnimalName array is $AnimalName[1] , with the value dogs .
Instead of referring to elements by their index number, we can use a third type of
variable: the hash , that allows us to map elements using a text identifier or key . As
shown in Example 16-3, we can store the animal counts in a hash called %Animals , with
the animal names as the key.
Example 16-3. Perl script using hash variables
#!/usr/bin/perl
use strict;
print "\nHash:\n";
my %Animals=( cats=>3, dogs=>7, fish=>4);
my $Total= $Animals{cats}+ $Animals{dogs}+ $Animals{fish};
 
Search WWH ::




Custom Search