Is perl's each function worth using?
Posted
by eugene y
on Stack Overflow
See other posts from Stack Overflow
or by eugene y
Published on 2010-03-07T14:10:24Z
Indexed on
2010/03/08
1:40 UTC
Read the original article
Hit count: 374
From perldoc -f each we read:
There is a single iterator for each hash, shared by all
each
,keys
, andvalues
function calls in the program; it can be reset by reading all the elements from the hash, or by evaluatingkeys HASH
orvalues HASH
.
The iterator is not reset when you leave the scope containing the each()
, and this can lead to bugs:
my %h = map { $_, 1 } qw(1 2 3);
while (my $k = each %h) { print "1: $k\n"; last }
while (my $k = each %h) { print "2: $k\n" }
Output:
1: 1
2: 3
2: 2
What are the common workarounds for this behavior? And is it worth using each
in general?
© Stack Overflow or respective owner