Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

perl, removing elements from array in for loop

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, "
";
    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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...