in reply to RFC: List::Extract

By using reverse twice combined with grep and map you can splice out the elements you want in one fell swoop.

use strict; use warnings; my @array = ( 3, 13, 73, 4, 29, 38 ); print qq{Before:\n}, qq{ @array\n}; my $rcExtract = sub { my $toTest = shift; return $toTest > 31 ? 1 : 0; }; my @extracted = reverse map { splice @array, $_, 1 } grep { $rcExtract->( $array[ $_ ] ) } reverse 0 .. $#array; print qq{After:\n}, qq{ @array\n}, qq{ @extracted\n};

The output.

Before: 3 13 73 4 29 38 After: 3 13 4 29 73 38

I hope this is of interest.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: RFC: List::Extract
by lodin (Hermit) on Nov 24, 2007 at 23:09 UTC

    Nice. This instantly reminded me about this node of mine, where I did almost the same thing. But I didn't think too much of it then. Thanks for reminding me.

    I think it's just, not far but enough, across the line where it's worth putting in a module though.

    lodin

      I hadn't seen your node as that thread happened while I was away on holiday watching madmen race motorcycles on the Isle of Man :-)

      I find reverse useful in a lot of situations and have advocated it's use before. What I particularly like is the way you can apply it in both list and scalar contexts, the latter to reverse a string. I use both in this post.

      Perl is just full of amazing tools. I love it.

      Cheers,

      JohnGG

Re^2: RFC: List::Extract
by kyle (Abbot) on Nov 25, 2007 at 03:23 UTC

    I like it!

    I wonder, though, what the performance hit is of looping over the list twice vs. once. Without doing any benchmarking, I suspect that it depends on the size of the list and how many elements are removed/kept.

    Just a thought.

      I have put together a benchmark testing lodin's code and the double-grep plus merlyn's and my code against different sized arrays and sifting out differing amounts of data. I couldn't get to grips with the subroutine prototype so I took that out of merlyn's routine. Here is the code.

      Here's the results.

      It seems to show that my code has a bit of an advantage when the arrays are not too large and when less data is being sifted out. It is noticeable that merlyn's code isn't impacted the more data that is sifted whereas mine is. I guess that is because he is always building two arrays whereas my map / splice has to do more work the more data is sifted. Also note the sudden elevation of twoGreps with large arrays for the 30%, 50% and 70% sifts but not for 10% or 90%.

      I've cocked up benchmarks before, however, so take all this with a pinch of salt. I won't be surprised if somebody tells me I've done the same this time.

      I hope this is of interest.

      Cheers,

      JohnGG