RE: [ID 20010720.006] each() fails when passed a subroutine that returns a hashref
[email protected] ("Wilson, Doug") Fri, 20 Jul 2001 12:26:39 -0700
| Newsgroups | perl.bugmongers,perl.perl5.porters |
|---|---|
| Message-ID | <[email protected]> |
> When each() is passed a subroutine that returns a reference
> to a hash, it
> causes an infinite loop. Tested on 5.00503 and 5.6.1.
> sub makeref {
> my $foo = {
> bar => [1, 2, 3],
> blah => [qw/a b c/],
> };
> return $foo;
> }
> while (my ($k, $v) = each %{makeref()}) {
> print "$k - @$v\n";
> }
Not a bug, IMHO.
makeref is returning a reference to a brand new hash
with a brand new iterator. And its the hash that
has an iterator assigned to it, not the call to each().
each() cannot know that a hash with the same value will
be returned.
Imagine doing this:
my $href1 = { aa => 1, cc => 3 };
my $href2 = { bb => 3, dd => 4 };
my $flip_flop;
sub return_ref {
$flip_flop = ! $flip_flop;
$flip_flop ? $href1 : $href2;
}
while (my ($k, $v) = each %{return_ref()}) {
print "$k $v\n";
}
'Fixing' the 'bug' would break this example.
----
Doug