![]() |
|
good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
while( each ... ) caught in an infinite loopby johngg (Canon) |
on Mar 31, 2009 at 10:34 UTC ( [id://754380]=perlquestion: print w/replies, xml ) | Need Help?? |
johngg has asked for the wisdom of the Perl Monks concerning the following question: I have a script that seems to hang and I have narrowed the problem down to the point where the code iterates, using each, over a de-referenced hash reference that is returned by a subroutine, i.e. each %{ sub { return { ... } }->( ... ) }. The each call keeps returning the first key/value pair rather than presenting the pairs in turn, thus looping for ever. The hang can be cured by storing the returned reference in an intermediate scalar variable before doing the each but I am curious as to why each is failing in this case. The documentation says:- ... There is a single 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. ... which might imply that keys and values would also have problems in this construct but that is not the case. The following code presents a minimal working example to demonstrate the problem. It first runs the code using the intermediate scalar variable and then repeats the exercise without it. Note that I am forced to bail out of the while( ( $k, $v ) = each %{ ... } ) { ... } using a counter to avoid an infinite loop.
The output.
As you can see, while keys and values produce the expected output when dispensing with the intermediate scalar, each gets nowhere fast. I have tested the code using Perl 5.10.0 under Cygwin and ActiveState Perl 5.8.8 under Windows XP. The fact that the interpreter accepts the syntax and the each attempts to iterate over the hash and fails where keys and values succeed makes me wonder whether this is, perhaps, a small bugette rather than my code trying to do something outside the bounds of the language. Should each be able to operate directly on the de-referenced return from the subroutine just like keys and values or is my code invalid? Cheers, JohnGG
Back to
Seekers of Perl Wisdom
|
|