显然,我不需要这个;我只是好奇这里发生了什么。我错过了一些简单的东西吗?我可以在所有版本的 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";
}
输出
deleted one; remaining: zero two
deleted zero; remaining: two
deleted two; remaining:
man perlfunc
(each) 没有解释为什么当$k
分配为 0 时 while 循环继续。代码表现得好像while
循环上的条件是($k = each %h, defined $k)
。
如果循环条件实际更改为,
($k = each %h, $k)
那么它确实会$k = 0
按预期停止。
它还停留在$k = 0
以下重新实现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";
}
只输出:
deleted one; remaining: zero two