perl,在for循环中从数组中删除元素 [英] perl, removing elements from array in for loop

查看:345
本文介绍了perl,在for循环中从数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将始终在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的任何部分是一个数组,如果您将foreach弄糊涂了 在循环体内添加或删除元素,例如使用拼接. 所以不要那样.

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 :

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆