List::Slice - Slice-like Operations for Lists
How many times have you needed to do this?
my @found_names = grep { /^[A-D]/ } @all_names;
my @topfive = @found_names[0..4];
Or worse, this.
my @topfive = ( grep { /^[A-D]/ } @all_names )[0..4];
Or this.
my @bottomfive = @names < 5 ? @names : @names[$#names-5..$#names];
Or this.
my @names
= map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
grep { $_->[1] > $now }
map { [ $_->{name}, parse_date( $_->{birthday} ) ] }
@all_users;
my @topfive = @names[0..4];
There's got to be a better way!
Now there is! Introducing: List::Slice!
With List::Slice, you can grab the front or back of any list without clumsy syntax or wasteful arrays.
Get the first elements of a list with the head
function.
use List::Slice qw( head );
my @topfive = head 5, grep { /^[A-D]/ } @all_names;
Get the last elements of a list with the tail
function.
use List::Slice qw( tail );
my @bottomfive = tail 5, @names;
You can even insert functions in to the middle of long stream processes to improve performance! Why deref things that will just be thrown away?
use List::Slice qw( head );
my @topfive
= map { $_->[0] }
head 5,
sort { $a->[1] <=> $b->[1] }
grep { $_->[1] > $now }
map { [ $_->{name}, parse_date( $_->{birthday} ) ] }
@all_users;
Stop taking up useless space with arrays that are sliced once and discarded. Stop searching for postfix slice syntax around lengthy list processing operations.
Slice your lists, with List::Slice!
hello,
i did it for a while (an on-demand way)
using Perlude:
use Perlude;
my @foo = fold take 5, fillter {/foo/}
sub { > // () }
This is really cool (and simple)—I didn't expect it to be XS.
Maybe you could write about this module for PerlTricks! The very simple glue code could be a nice introduction to XS. I don't think David has any articles like that yet.
Awesome, I had this request in #perl-help the other day, and hopefully I can now never run into auto-vivification of dereferenced array-ref members again (still don't understand why that happens.)
Yeah, that's a good idea. I'd love to convince more people that XS isn't as scary and terrible as it seems.
I can't read this. The gifs are way too distracting.