Databases Reference
In-Depth Information
Notice that the while loop does not include a particular place for initializing or incre-
menting the counter. In fact, we generally use the for loop when we know exactly how
many times we want to run the loop, and we use other loop constructs such as the
while loop when we don't.
The do...while loop is almost identical to the while loop, with one difference: the
condition is first evaluated only after the loop body has been executed once. This means
that the body is executed even if the condition is not true, which is useful in some
circumstances:
my $counter=1;
do
{
print "\nThe value is: $counter";
$counter++;
}while($counter<=10);
Finally, the until loop is identical to the while loop but inverts the condition; the loop
is executed as long as the condition is false:
my $counter=1;
until($counter>10)
{
print "\nThe value is: $counter";
$counter++;
}
Iterating Through Arrays and Hashes
Earlier in “Arrays and Hashes,” we accessed the individual scalar elements in the
@Animals array by their index numbers—for example:
my $Total=
$Animals{$AnimalName[0]}+
$Animals{$AnimalName[1]}+
$Animals{$AnimalName[2]};
We can use the foreach construct to walk through all the keys of the %Animals hash
(given by keys %Animals ) and assign each value in turn to the scalar variable
$AnimalName :
my %Animals=( "cats"=>3, "dogs"=>7, "fish"=>4);
my $Total=0;
print "Pet roll call:\n".
"===========\n";
foreach my $AnimalName (keys %Animals)
{
$Total+=$Animals{$AnimalName};
print "$AnimalName:\t$Animals{$AnimalName}\n";
}
 
Search WWH ::




Custom Search