each HASHPerl's each() function is used to iterate (loop) through the the key / value pairs of a HASH. Each key / value pair is returned as a two-element list.
%contact = ('name' => 'Bob', 'phone' => '111-111-1111');In the above example, we start with a simple hash of our contact Bob and his phone number. The each function takes this regular hash as input, and is couched in a while loop. Here is the each function standing on it's own:
while (($key, $value) = each %contact) {
print "$key=$value\n";
}
($key, $value) = each %contactEvery time the each function is called, it grabs an element out of the hash and puts them in the $key and $value strings. When couched in the while statement it will loop through each element of the hash and pass them off to the print statement.
There are a couple of things to keep in mind when using the each function. Because of the way Perl works with hashes, the elements will be returned in random order. Also, the each function does not remove the elements from the hash - the hash is unaffected by the looping process.
