Subject: | wish: shift_all and pop_all |
Date: | Thu, 4 Jul 2013 13:20:36 +0000 |
To: | "bug-List-MoreUtils [...] rt.cpan.org" <bug-List-MoreUtils [...] rt.cpan.org> |
From: | "Majewsky, Stefan" <stefan.majewsky [...] sap.com> |
I've run across the following pattern in my code:
my @target;
push @target, shift @source while condition($source[0]);
This could be useful as a generic function shift_all(), which removes and returns all leading elements of @source which match the given predicate:
@target = shift_all { condition($_) } @source;
In a way, this is similar to List::UtilsBy::extract_by(), but it stops at the first non-matching element rather than just skipping non-matches. shift_all() is also similar to List::Util::before as in...
@target = before { not condition($_) } @source;
But shift_all() changes @source whereas before() does not.
And of course, if there's shift_all(), there should be pop_all(), too. Example:
my @source = 1..10;
@target1 = shift_all { $_ < 4 } @source; # 1..3
@target2 = pop_all { $_ > 7 } @source; # 8..10
# @source is (4..7) now
Regards
Stefan Majewsky