加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl,从for循环中的数组中删除元素

发布时间:2020-12-15 23:25:40 所属栏目:大数据 来源:网络整理
导读:以下代码是否始终在perl中运行? for loop iterating over @array { # do something if ($condition) { remove current element from @array }} 因为我在Java中知道这导致了一些异常,上面的代码现在对我有用,但我想确保它适用于perl中的所有情况.谢谢 解决方
以下代码是否始终在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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读