gpt4 book ai didi

perl - 当我在同一个散列上循环时,在 Perl 中从散列引用中删除一个键是否安全?为什么?

转载 作者:行者123 更新时间:2023-12-04 03:01:50 25 4
gpt4 key购买 nike

我基本上想这样做:

foreach my $key (keys $hash_ref) {

Do stuff with my $key and $hash_ref

# Delete the key from the hash
delete $hash_ref->{$key};
}

安全吗?为什么?

最佳答案

您不是迭代哈希,而是迭代 keys 返回的键列表在你开始循环之前。请记住

for my $key (keys %$hash_ref) {
...
}

大致相同
my @anon = keys %$hash_ref;
for my $key (@anon) {
...
}

从散列中删除不会导致任何问题。

each ,另一方面,确实迭代哈希。每次调用时, each返回不同的元素。然而,它仍然是安全的 delete当前元素!
# Also safe
while (my ($key) = each(%$hash_ref)) {
...
delete $hash_ref->{$key};
...
}

If you add or delete a hash's elements while iterating over it, entries may be skipped or duplicated--so don't do that. Exception: It is always safe to delete the item most recently returned by each()

关于perl - 当我在同一个散列上循环时,在 Perl 中从散列引用中删除一个键是否安全?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10853835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com