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
In reply to Unexpected persistence with each hash by Zaxo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |