I've written the module List::Gen on CPAN that provides an alternative way to do this:
use List::Gen qw/by/;
my @array = qw/zero one two three four five six/;
my @slice = map {$$_[0]} by 2 => @array;
by
partitions @array
into groups of two elements and returns an array of array references. map
then gets this list, so each $_
in the map will be an array reference. $$_[0]
(which could also be written $_->[0]
) then grabs the first element of each group that by
created.
Or, using the mapn
function which by
uses internally:
use List::Gen qw/mapn/;
my @slice = mapn {$_[0]} 2 => @array;
Or, if your source list is huge and you may only need certain elements, you can use List::Gen
's lazy lists:
use List::Gen qw/by gen/;
my $slicer = gen {$$_[0]} by 2 => @array;
$slicer
is now a lazy list (an array ref) that will generate it's slices on demand without processing anything that you didn't ask for. $slicer
also has a bunch of accessor methods if you don't want to use it as an array ref.