perl, removing elements from array in for loop

ぃ、小莉子 提交于 2019-12-18 08:32:38

问题


will the following code always work in perl ?

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

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


回答1:


Well, it's said in the 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.

It's a bit better with 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
  }

But I suppose the best option here would be just using grep:

@some_array = grep {
  # do something with $_
  some_condition($_);
} @some_array;


来源:https://stackoverflow.com/questions/16895001/perl-removing-elements-from-array-in-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!