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];

There's got to be a better way!

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!

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!

5 Comments

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.)

$ perl -wE 'my $a=[1,2,3]; say 0+@{$a}; say map { $_ // "undef" } @{$a}[0..10]; say 0+@{$a};'
3
123undefundefundefundefundefundefundefundef
11

I can't read this. The gifs are way too distracting.

Leave a comment

About preaction

user-pic I blog about Perl.