5.4.2 Each
The each function is one that you will find particularly useful when
you need to go through each element in the hash. The each function
returns each key-value pair from the hash one by one as a list of two
elements. You can use this function to run a while across the hash:
use strict;
my %table = qw/schmoe joe smith john simpson bart/;
my($key, $value); # @cc{Declare two variables at once}
while ( ($key, $value) = each(%table) ) {
# @cc{Do some processing on @scalar{$key} and @scalar{$value}}
}
This while terminates because each returns undef
when all the pairs have been exhausted. However, be careful. Any
change in the hash made will "reset" the each function for that
hash.
So, if you need to loop and change values in the hash, use the following
foreach across the keys:
use strict;
my %table = qw/schmoe joe smith john simpson bart/;
foreach my $key (keys %table) {
# Do some processing on $key and $table{$key}
}