perl,在for循环中从数组中删除元素 [英] perl, removing elements from array in for loop
问题描述
以下代码在 perl 中总是有效吗?
will the following code always work in perl ?
for loop iterating over @array {
# do something
if ($condition) {
remove current element from @array
}
}
因为我知道在 Java 中这会导致一些异常,所以上面的代码现在对我有用,但我想确保它适用于 perl 中的所有情况.谢谢
Because I know in Java this results in some Exceptions, The above code is working for me for now, but I want to be sure that it will work for all cases in perl. Thanks
推荐答案
嗯,文档:
如果 LIST 的任何部分是一个数组,如果你在循环体中添加或删除元素,例如使用 splice.所以不要那样做.
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:
如果在迭代时添加或删除散列的元素,条目可能会被跳过或重复——所以不要这样做.例外:在当前的实现,删除项目总是安全的最近由 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::>
But I suppose the best option here would be just using grep:
@some_array = grep {
# do something with $_
some_condition($_);
} @some_array;
这篇关于perl,在for循环中从数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!