in reply to using values and keys functions
On the other hand, each is a true iterator, and uses the hashes internal position iterator (cant think of the real name) to keep track of where it was.
Consider the following code:
It outputs:use strict; use warnings; { my %hash = ( 'a' => 1, 'b' => 2, 'c' => 3, ); foreach my $key (keys %hash) { print "$key = $hash{$key}\n"; foreach my $key (keys %hash) { print "\t$key\n"; } } }
c = 3
c
a
b
a = 1
c
a
b
b = 2
c
a
b
Now consider this code (on the same hash)
This results in an infinite loop because on each time through the while loop, each gives back the next key-value pair. By next I mean in the sense of checking the hash iterator. But the inner foreach loop calls keys on the same hash as the outer loop. keys and values both automatically reset the iterator, and create their return list by iterating thru the whole hash. And after getting to the end, the iterator is again reset for next time. Then, when the each is called again, the iterator says to return the first key-value pair.while ( my($key, $value) = each %hash ) { print "$key = $value\n"; foreach my $key (keys %hash) { print "\t$key\n"; } }
This can be seen by letting the infinite loop run a few times.
|
|---|