gpt4 book ai didi

arrays - perl,在for循环中从数组中删除元素

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

下面的代码总是在 perl 中工作吗?

for loop iterating over @array {
# do something
if ($condition) {
remove current element from @array
}
}

因为我知道在 Java 中这会导致一些异常,上面的代码现在对我有用,但我想确保它适用于 perl 中的所有情况。谢谢

最佳答案

嗯,这是在doc中说的:

If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.



each 好一点:

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: In the current implementation, it is always safe to delete the item most recently returned by each(), so the following code works properly:


 while (($key, $value) = each %hash) {
print $key, "\n";
delete $hash{$key}; # This is safe
}

但我想这里最好的选择就是使用 grep :
@some_array = grep {
# do something with $_
some_condition($_);
} @some_array;

关于arrays - perl,在for循环中从数组中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16895001/

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