以下代码是否始终在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;