Is there a compact Perl operation to slice alternate elements from an array?

A Perl array slice is the @ in front of the array name, then the list of indices you want:

 @array[@indices];

There's not a built-in syntax to select multiples, but it's not so hard. Use grep to produce a list of indices that you want:

 my @array = qw( zero one two three four five six );
 my @evens = @array[ grep { ! ($_ % 2) } 0 .. $#array ];

If you are using PDL, there are lots of nice slicing options.


There's array slices:

my @slice = @array[1,42,23,0];

There's a way to to generate lists between $x and $y:

my @list = $x .. $y

There's a way to build new lists from lists:

my @new = map { $_ * 2 } @list;

And there's a way to get the length of an array:

my $len = $#array;

Put together:

my @even_indexed_elements = @array[map { $_ * 2 } 0 .. int($#array / 2)];

Granted, not quite as nice as the python equivalent, but it does the same job, and you can of course put that in a subroutine if you're using it a lot and want to save yourself from some writing.

Also there's quite possibly something that'd allow writing this in a more natural way in List::AllUtils.

Tags:

Syntax

Perl