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.
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: " .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With