Zaxo has asked for the wisdom of the Perl Monks concerning the following question:
I was tinkering with item-by-item deletion of hashes, looking for something yet unsaid about Hash Entry Deallocation. Investigating the form while (%hash) {delete...}, I found behavior I hadn't expected. The seemingly sane,
continues to spin after the hash is depleted, endlessly printing ' => is done.'.my %foo; @foo{qw/ foo bar baz /} = 1 .. 3; while (%foo) { my $key = each %val; my $val = delete $foo{$key}; printf "%s => %s is gone.\n", $key, $val; }
The ugly variation,
works as expected.my %foo; @foo{qw/ foo bar baz /} = 1 .. 3; my @keys = keys %foo; while (%foo) { my $key = shift @keys; my $val = delete $foo{$key}; printf "%s => %s is gone.\n", $key, $val; }
I first suspected that modifying the hash upset each's bookkeeping, but then how could the more conventional,
work?while (my ($key, $val) = each %hash) { delete $hash{$key}; printf "%s => %s is gone.\n", $key, $val; }
Does anyone know why this happens?
After Compline,
Zaxo
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Unexpected persistence with each hash
by dragonchild (Archbishop) on Jul 01, 2003 at 03:43 UTC | |
by demerphq (Chancellor) on Jul 01, 2003 at 07:53 UTC | |
by Zaxo (Archbishop) on Jul 01, 2003 at 03:56 UTC | |
|
Re: Unexpected persistence with each hash
by bwana147 (Pilgrim) on Jul 01, 2003 at 09:45 UTC |