Alex Rivera | Logout

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

Asked 2010-10-13T15:56:08.917
18

If I have an array myarray in Python, I can use the slice notation

myarray[0::2]

to select only the even-indexed elements. For example:

>>> ar = [ "zero", "one", "two", "three", "four", "five", "six" ]
>>> ar [ 0 : : 2 ]
['zero', 'two', 'four', 'six']

Is there a similar facility in Perl?

Edit
Report

1 Answer

25

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.

answered 2010-10-13T16:03:08.150

Your Answer