spandox has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Foreach for array pruning?
by Zaxo (Archbishop) on Jul 02, 2004 at 18:19 UTC | |
by demerphq (Chancellor) on Jul 02, 2004 at 21:46 UTC | |
|
Re: Foreach for array pruning?
by pbeckingham (Parson) on Jul 02, 2004 at 18:13 UTC | |
|
Re: Foreach for array pruning?
by dragonchild (Archbishop) on Jul 02, 2004 at 18:34 UTC | |
|
Re: Foreach for array pruning?
by diotalevi (Canon) on Jul 02, 2004 at 18:00 UTC | |
|
Re: Foreach for array pruning? (Updated)
by BrowserUk (Patriarch) on Jul 02, 2004 at 19:55 UTC | |
by spandox (Novice) on Jul 02, 2004 at 21:43 UTC | |
by BrowserUk (Patriarch) on Jul 02, 2004 at 22:34 UTC | |
by spandox (Novice) on Jul 03, 2004 at 05:02 UTC | |
by duff (Parson) on Jul 02, 2004 at 21:52 UTC | |
|
Re: Foreach for array pruning?
by CombatSquirrel (Hermit) on Jul 02, 2004 at 19:54 UTC |