I don't need this, obviously; I'm just curious about what's going on here. Am I missing something simple? Can I rely on this behaviour in all versions of Perl?)
Perl v5.8.8:
%h = ( 0=>'zero', 1=>'one', 2=>'two' );
while ($k = each %h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
outputs
deleted one; remaining: zero two
deleted zero; remaining: two
deleted two; remaining:
man perlfunc
(each) does not explain why the
while loop continues when $k
is assigned 0.
The code behaves as if the condition on the while
loop
were ($k = each %h, defined $k)
.
If the loop condition is actually changed to
($k = each %h, $k)
then it does indeed
stop at $k = 0
as expected.
It also stops at $k = 0
for the following
reimplementation of each
:
%h = ( 0=>'zero', 1=>'one', 2=>'two' );
sub each2 {
return each %{$_[0]};
}
while ($k = each2 \%h) {
$v = delete $h{$k};
print "deleted $v; remaining: @h{0..2}\n";
}
outputs just:
deleted one; remaining: zero two