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,
you can read the perldoc on each
When the hash is entirely read, a null array is returned in list context (which when assigned produces a false (0) value), and "undef" in scalar context. The next call to "each" after that will start iterating again. There is a sin‐ gle iterator for each hash, shared by all "each", "keys", and "values" function calls in the program; it can be reset by reading all the elements from the hash, or by evaluating "keys HASH" or "values HASH".
therefore, you can use keys %set in your code to iterate again (due to you "last" statement)
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 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.