This is a little bit of a question but it may just be a feature request.
Is there a way to, from within a foreach, drop the element you are working with from the array.
Example: @moo = (1 .. 10); foreach (@moo) { if ($_ % 2 > 0) { DROP();} # <----- is what I would LOVE # to do }
Such that the result would be @moo would be (2,4,6,8,10)
Yes I know I can there are all sorts of ways to get the same effect.
Grep: @moo = grep {($_ % 2 > 0)?0:1;} @moo; Or easier to add more complex code if you: @moo = grep {; {if ($_ % 2 > 0){ 0; last; } 1;}} @moo; # PS why do I need that first ';' - I don't know but I do For Loop: for (my $i=0;$i<@moo;$i++) { if ($moo[$i] % 2 > 0) {splice @moo, $i, 1;} } # wow is this slow
But here is what I dislike - the inefficiency of having to use temporary variables or reassaining an entire list.
If a grep could work in place that would be the answer - but it can't. That pretty much doubles the amount of time it takes to work on the array - the assignment back to the original list.
Why is this important to me? I often find myself working with huge arrays. I would love to prune the data in a simple - yet readable away.
In reply to Foreach for array pruning? by spandox
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |