Subject: | delete while iterating with each |
perldoc -f each says:
It is always safe to delete the item most recently returned by "each()",
so the following code
works properly:
while (($key, $value) = each %hash) {
print $key, "\n";
delete $hash{$key}; # This is safe
}
But this is not true for hash tied with Tie::IxHash:
use v5.10;
use Tie::IxHash;
use Test::More;
use Data::Dumper;
tie my %h, 'Tie::IxHash';
$h{a} = 1;
$h{b} = 2;
$h{c} = 3;
$h{d} = 4;
$h{e} = 5;
while (my ($k) = each %h) {
if ($k ~~ [qw/b d e/]) {
delete $h{$k};
}
}
is(scalar(keys(%h)), 2) or diag Dumper(\%h);
done_testing;
__END__
not ok 1
# Failed test at t.pl line 19.
# got: '3'
# expected: '2'
# $VAR1 = {
# 'a' => 1,
# 'c' => 3,
# 'e' => 5
# };
1..1
# Looks like you failed 1 test of 1.
oleg@host-10-198-139-17:/tmp$ perl t.pl
not ok 1
# Failed test at t.pl line 19.
# got: '3'
# expected: '2'
# $VAR1 = {
# 'a' => 1,
# 'c' => 3,
# 'e' => 5
# };
1..1
# Looks like you failed 1 test of 1.