在使用 each时,您应该注意的一件事是
将“状态”添加到散列的副作用(散列必须记住
下一个键是什么),
which iterate over the whole hash in one go, this is usually not a
然而,你会遇到很难找到的问题(我从
经验;) ,当使用 each与语句,如
last或 return在您之前退出 while ... each循环
已经处理了所有的钥匙。
在这种情况下,散列将记住它已经返回的键,并且
when you use each on it the next time (maybe in a totaly unrelated piece of
代码) ,它将继续在这个位置。
Example:
my %hash = ( foo => 1, bar => 2, baz => 3, quux => 4 );
# find key 'baz'
while ( my ($k, $v) = each %hash ) {
print "found key $k\n";
last if $k eq 'baz'; # found it!
}
# later ...
print "the hash contains:\n";
# iterate over all keys:
while ( my ($k, $v) = each %hash ) {
print "$k => $v\n";
}
这张照片:
found key bar
found key baz
the hash contains:
quux => 4
foo => 1
while ( my ($key,$val) = each %a_hash ) {
print "$key => $val\n";
last if $val; #exits loop when $val is true
}
# but "each" hasn't reset!!
while ( my ($key,$val) = each %a_hash ) {
# continues where the last loop left off
print "$key => $val\n";
}