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
- Is there any other module that does the same thing? (I haven't found any on CPAN.)
- Do you have any suggestion for a better name?
- Do you think that modifications to $_ should be discarded for elements in the returned list?
- Do you think that modifications to $_ should be discarded for elements kept in the array?
lodin
Update: Uploaded as List::Extract to CPAN.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.