Arnon Weinberg Arnon Weinberg - 2 months ago 12
Perl Question

Perl: Is it possible to iterate over an anonymous hash?

It's easy enough to iterate over a list:

foreach my $elem ( 1, 2, 3, 4, 5 ) {
say $elem;
}


or an anonymous array:

foreach my $elem (@{[ 1, 2, 3, 4, 5 ]}) {
say $elem;
}


But is it possible to do the same for an anonymous hash? I tried:

while (my ($key, $value) = each (%{{ a => 1, b => 2, c => 3 }})) {
say "$key=$value";
}


but I get an infinite loop.

Answer

A foreach loop evaluates its expression once. while, on the other hand, evaluates its expression once each pass. That means you are repeatedly creating a new hash and grabbing its first element.

You could do the following:

use List::Util 1.29 qw( pairs );

for my $pair ( pairs %{ { a => 1, b => 2, c => 3 } } ) {
   my ( $key, $val ) = @$pair;
   ...
}

But just like your second snippet is a needlessly wasteful version of your first snippet, the above is a needlessly wasteful version of the following:

use List::Util 1.29 qw( pairs );

for my $pair ( pairs a => 1, b => 2, c => 3 ) {
   my ( $key, $val ) = @$pair;
   ...
}
Comments