each returns a list. $key is now always 2, unless it's 0.
Not so. each is context sensitive as are most things in Perl (you knew that, silly :-)
Actually there is an interesting point here, iirc when you do a Tie::Hash implementation the EACH() sub only returns the key. Perl then automatically follows with a FETCH() to get the value (and I think it does so regardless of the context as well that the each keyword is used in). This is a bit annoying as often in this situation you need to do the same work to get the key or the value and finding one gives you the other. (You can play games to optimise this but its still annoying.)
Oh - try seeing what the stringification of %foo is, even when it's empty. It's not what you think.
I would have thought it would be false when the hash is empty, and suprise suprise it is. :-)
The only change Zaxo needed to make to his code was as you pointed out to change the %val to %foo. Your points about strictures etc is good of course :-)
my %foo; @foo{qw/ foo bar baz /} = 1 .. 3; printf "%%foo = %s { %s } = ( %s )\n",\%foo,scalar %foo, join(",",map "$_ => $foo{$_}",keys %foo); while (%foo) { my $key = each %foo; my $val = delete $foo{$key}; printf "%s => %s is gone.\n", $key, $val; printf "%%foo = %s { %s } = ( %s )\n",\%foo,scalar %foo, join(",",map "$_ => $foo{$_}",keys %foo); }
%foo = HASH(0x1ab298c) { 2/8 } = ( foo => 1,baz => 3,bar => 2 ) foo => 1 is gone. %foo = HASH(0x1ab298c) { 1/8 } = ( baz => 3,bar => 2 ) baz => 3 is gone. %foo = HASH(0x1ab298c) { 1/8 } = ( bar => 2 ) bar => 2 is gone. %foo = HASH(0x1ab298c) { 0 } = ( )
In reply to Re: Re: Unexpected persistence with each hash
by demerphq
in thread Unexpected persistence with each hash
by Zaxo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |