in reply to Re^2: Foreach for array pruning? (Updated)
in thread Foreach for array pruning?
I'm not quite sure what you mean by "misses the point"?
I thought you were looking for a way to avoid your percieved inefficiencies of using grep to filter large arrys. The only 'inefficiency' that really exists is that (notionally) a list is created on one side of the grep which is then filtered and assigned back to the array on the other. Ie. Perl trades space for time.
Given the way Perl implements it's arrays, there is no trivial way of removing an element from the middle.
[@myarray]-->[ 0 ]->[ value 1 ] [ 1 ]->[ value 2 ] [ 2 ]->[ value 3 ] [ 3 ]->[ value 4 ] [ 4 ]->[ value 5 ]
To remove a value from the middle (say element 2) in-place, you have to ripple the pointers.
[@myarray]-->[ 0 ]---->[ value 1 ] [ 1 ]---->[ value 2 ] [ 2 ]-\ [ 3 ]-\\->[ value 4 ] \->[ value 5 ]
In effect (if not in exact implementation), is to copy pointers from the old list into a new one omiting those that fail the test. Then discard the old array if the destination is the same as the source. Very efficient cpu-wise but does require a extra memory.
Doing it in-place avoids the extra memory, but there is no way to void the ripple. That's basically what my snippet did. It's obviously not going to be as fast, though I was surprised how little slower it was. Whether it would be possible to add an optimisation to grep to do this in line if the dest == src I'm not sure. I know that sort has a similar 'in-place' optimisation for dest == src invocations.
With respect to the need for the ';'... It's required to allow the parser to determine that your inner code block
@moo = grep {; {if ($_ % 2 > 0){ 0;last; } 1;}} @moo;
Is a code block and not an anonymous hash. More typically this is done with a unary '+'
@moo = grep { +{if ($_ % 2 > 0){ 0;last; } 1;} } @moo;
Alternatively, you could avoid the need for the inner block completely and do
@moo = grep { not ( $_ % 2 ) } @moo;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Foreach for array pruning? (Updated)
by spandox (Novice) on Jul 03, 2004 at 05:02 UTC |