Why doesn’t Perl’s each() iterate through the entire hash the second time?

each uses a pointer associated with the hash to keep track of iteration. It does not know that the first while is different from the second while loop, and it keeps the same pointer between them.

Most people avoid each for this (and other) reasons, instead opting for keys:

for my $key (keys %hash){
    say "$key => $hash{$key}";
}

This gives you control over the iteration order, as well:

for my $key (sort keys %hash){
    say "$key => $hash{$key}";
}

Anyway, if you are going to end the loop early, avoid each.

BTW, functional programming advocates should take this opportunity to point out the disadvantages of hidden state. What looks like a stateless operation (“loop over each pair in a table”) is actually quite stateful.

Leave a Comment