Description
I have a module I currently call List::Extract that has a single subroutine: extract. It's used like
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 tomy @extracted = extract { ... } @list;
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
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 @extracted = grep { ... } @list; @list = grep { not ... } @list;
and still I iterate the array twice.my $filter = sub { ... }; my @extracted = grep { $filter->() } @list; @list = grep { not $filter->() } @list;
My questions
lodin
Update: Uploaded as List::Extract to CPAN.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: RFC: List::Extract
by johngg (Canon) on Nov 24, 2007 at 21:48 UTC | |
by lodin (Hermit) on Nov 24, 2007 at 23:09 UTC | |
by johngg (Canon) on Nov 24, 2007 at 23:43 UTC | |
by kyle (Abbot) on Nov 25, 2007 at 03:23 UTC | |
by johngg (Canon) on Nov 27, 2007 at 13:48 UTC | |
|
Re: RFC: List::Extract
by eserte (Deacon) on Nov 24, 2007 at 21:11 UTC | |
by doom (Deacon) on Nov 25, 2007 at 00:22 UTC | |
by lodin (Hermit) on Nov 25, 2007 at 01:37 UTC | |
by mreece (Friar) on Nov 25, 2007 at 03:52 UTC | |
by doom (Deacon) on Nov 25, 2007 at 22:13 UTC | |
by doom (Deacon) on Nov 25, 2007 at 22:43 UTC | |
|
Re: RFC: List::Extract
by merlyn (Sage) on Nov 25, 2007 at 14:16 UTC | |
|
Re: RFC: List::Extract
by Fletch (Bishop) on Nov 25, 2007 at 14:53 UTC |