I have a simple script trying to learn about hashes in Perl.
#!/usr/bin/perl
my %set = (
-a => 'aaa',
-b => 'bbb',
-c => 'ccc',
-d => 'ddd',
-e => 'eee',
-f => 'fff',
-g => 'ggg'
);
print "Iterate up to ggg...\n";
while ( my ($key, $val) = each %set ) {
print "$key -> $val \n";
last if ($val eq 'ggg');
}
print "\n";
print "Iterate All...\n";
while ( my ($key, $val) = each %set ) {
print "$key -> $val \n";
}
print "\n";
I am surprised by the output:-
Iterate upto ggg...
-a -> aaa
-c -> ccc
-g -> ggg
Iterate All...
-f -> fff
-e -> eee
-d -> ddd
-b -> bbb
I understand that the keys are hashed so the first output can be ‘n’ elements depending on the internal ordering. But why am I not able to just loop the array afterward? What’s wrong ?
Thanks,
eachuses 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
eachfor this (and other) reasons, instead opting forkeys:This gives you control over the iteration order, as well:
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.