Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

perl

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?

Thanks.

like image 766
Rhubbarb Avatar asked Oct 13 '10 15:10

Rhubbarb


People also ask

How do I extract an element from an array in Perl?

Array slicing can be done by passing multiple index values from the array whose values are to be accessed. These values are passed to the array name as the argument. Perl will access these values on the specified indices and perform the required action on these values. print "Extracted elements: " .

What is array slicing in Perl?

You can also extract a "slice" from an array - that is, you can select more than one item from an array in order to produce another array.

How do I dereference an array in Perl?

Dereferencing an array If you have a reference to an array and if you would like to access the content of the array you need to dereference the array reference. It is done by placing the @ symbol (the sigil representing arrays) in-front of the reference.


1 Answers

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.

like image 194
brian d foy Avatar answered Oct 12 '22 12:10

brian d foy