Node:Each, Previous:Keys and Values, Up:Hash Functions



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);  # Declare two variables at once
     while ( ($key, $value) = each(%table) ) {
         # Do some processing on $key and $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}
     }