rovf has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: This "each" goes to endless loop each time...
by moritz (Cardinal) on Jun 19, 2008 at 10:48 UTC | |
by rovf (Priest) on Jun 19, 2008 at 10:57 UTC | |
|
Re: This "each" goes to endless loop each time...
by GrandFather (Saint) on Jun 19, 2008 at 11:04 UTC | |
by rovf (Priest) on Jun 19, 2008 at 11:27 UTC | |
by GrandFather (Saint) on Jun 19, 2008 at 20:03 UTC | |
by rovf (Priest) on Jun 20, 2008 at 07:50 UTC | |
|
Re: This "each" goes to endless loop each time...
by tfoertsch (Beadle) on Jun 19, 2008 at 11:19 UTC |