在我循环使用相同的哈希时,在Perl中从哈希引用中删除密钥是否安全?为什么?

May*_*yeu 10 perl hash key

我基本上想要这样做:

foreach my $key (keys $hash_ref) {

    Do stuff with my $key and $hash_ref

    # Delete the key from the hash
    delete $hash_ref->{$key};
}
Run Code Online (Sandbox Code Playgroud)

安全吗?为什么?

ike*_*ami 17

你没有迭代哈希,你keys在你开始循环之前迭代返回的键列表.请记住

for my $key (keys %$hash_ref) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

大致相同

my @anon = keys %$hash_ref;
for my $key (@anon) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

从哈希中删除不会导致任何问题.


each另一方面,它会迭代哈希.每次调用它时,都会each返回一个不同的元素.然而,它对delete当前元素仍然是安全的!

# Also safe
while (my ($key) = each(%$hash_ref)) {
   ...
   delete $hash_ref->{$key};
   ...
}
Run Code Online (Sandbox Code Playgroud)

如果在迭代时添加或删除哈希的元素,则可以跳过或复制条目 - 因此不要这样做.例外:删除每个()最近返回的项目总是安全的