Arnon Weinberg
Arnon Weinberg

Reputation: 901

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.

Upvotes: 3

Views: 871

Answers (1)

ikegami
ikegami

Reputation: 386541

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 and complex version of your first snippet, the above is a needlessly wasteful and complex 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;
   ...
}

Upvotes: 12

Related Questions