I've got a problem using the result of a function which has the following behaviour: When it is called in list context, it returns a hash; but when it is called in scalar context, it returns a reference to a hash. My problem relates to the second case, when the result of the function call is used in a 'while .... each ...' construct. Here is the example code:
The first while works fine. %env was set by calling e in list context, and it is the hash. The second while loops forever, returning the same element of the hash all the time.use warnings; use strict; sub e() { my %result=(A=>1,B=>2); wantarray ? %result : \%result; } my %env=e; $|=1; while (my ($var,$val) = each %env) { print "(hash) $var=$val\n"; } while (my ($var,$val) = each %{ &e }) { print "(ref) $var=$val\n"; }
My reasoning was as follows: Inside %{...}, the call to e is done in a scalar context, so it should return the reference to the hash, which then would be passed to each. The call to each in turn is in list context, so we should iterated over the hash. However, it looks as if the iterator would be reset every time.
Could someone explain to me, what is going on her and why, and how to properly iterate over a hash given a hash reference? Well, I can of course use the keys function, but I wonder whether it is possible to do with each.
In reply to This "each" goes to endless loop each time... by rovf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |