Traversing a Hash

Problem

You want to perform an action on each entry (i.e., each key-value pair) in a hash.

Solution

Use each with a while loop:

while(($key, $value) = each(%HASH)) {
    # do something with $key and $value
}

Or use keys with a foreach loop, unless the hash is potentially very large:

foreach $key (keys %HASH) {
    $value = $HASH{$key};
    # do something with $key and $value
}

Discussion

Here’s a simple example, iterating through the %food_color hash from the introduction.

# %food_color per the introduction
while(($food, $color) = each(%food_color)) {
    print "$food is $color.\n";
}

                  Banana is yellow.
               
                  Apple is red.
               
                  Carrot is orange.
               
                  Lemon is yellow.

foreach $food (keys %food_color) {
    my $color = $food_color{$food};
    print "$food is $color.\n";
}

                  Banana is yellow.
               
                  Apple is red.
               
                  Carrot is orange.
               
                  Lemon is yellow.

We didn’t really need the $color variable in the foreach example because we only use it once. Instead, we could have just written:

print "$food is $food_color{$food}.\n"

Every time each is called on the same hash, it returns the “next” key-value pair. We say “next” because the pairs are returned in the order the underlying lookup structure imposes on them, and this order is almost never alphabetic or numeric. When each runs out of hash elements, it returns the empty list (), which tests false and terminates the while loop.

The foreach example uses keys, which constructs an entire list containing every key from hash, before the loop even begins executing. The advantage to using ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.