Description

I have a module I currently call List::Extract that has a single subroutine: extract. It's used like

my @extracted = extract { ... } @list;
It removes and returns the elements that tests true for the code in the block, like grep and splice combined. The code above is equivalent to
my @extracted; my $c = 0; while ($c < @$list) { local *_ = \$list->[$c]; if (do { ... }) { push @extracted, splice @$list, $c, 1; } else { $c++; } }

Motivation

The reason I wrote this routine was that I haven't found any idiom to achieve the same thing that I'm pleased with. The only other way that I'm lazy enough to write that's significally shorter and logically simpler than the code above is

my @extracted = grep { ... } @list; @list = grep { not ... } @list;
but I don't like that, mostly because it duplicates the logic in the grep block, and factoring it out would make it unpretty again:
my $filter = sub { ... }; my @extracted = grep { $filter->() } @list; @list = grep { not $filter->() } @list;
and still I iterate the array twice.

My questions

lodin

Update: Uploaded as List::Extract to CPAN.


In reply to RFC: List::Extract by lodin

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.