Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all elements from index N to the end from an anonymous Perl array?

Tags:

arrays

perl

In Perl 5, when we have a named array, e.g. @a, getting the elements from index $N onwards is simple with a bit of slicing:

my @result = @a[$N..$#a];

Is there a standard way to do the same with an anonymous array, without having to supply the length explicitly? I.e. can this:

my @result = (0,1,2,3,4,5)[2..5];

or, more specifically, this:

my @result = (0,1,2,3,4,5)[$N..5];

be converted to something that does not need the upper range limit to be explicit? Perhaps some obscure Perl syntax? Maybe a bit of dicing instead of slicing?

PS: I have already written this as a function - I am looking for a more self-contained approach.

like image 777
thkala Avatar asked Nov 09 '11 21:11

thkala


People also ask

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

Arrays can store any type of data and that data can be accessed in multiple ways. These values can be extracted by placing $ sign before the array and storing the index value of the element to be accessed within the square brackets.

How do I get the last index of an array in Perl?

Perl provides a shorter syntax for accessing the last element of an array: negative indexing. Negative indices track the array from the end, so -1 refers to the last element, -2 the second to last element and so on.

How do you find the index of an element in an array in Perl?

Perl access array elementsArray elements are access by their indexes. The first index has value 0. The last index is $#vals . Array elements can be accessed from the end by using negative indexes.

What does Unshift do in Perl?

unshift() function in Perl places the given list of elements at the beginning of an array. Thereby shifting all the values in the array by right. Multiple values can be unshift using this operation. This function returns the number of new elements in an array.


3 Answers

You can splice it:

@result = splice @{[0..$M]}, $N;  # return $N .. $M
like image 161
mob Avatar answered Oct 15 '22 15:10

mob


You don't need to give an array ref a name if you set it as the topic:

    sub returns_array_ref {[1 .. 5]}

    my @slice = map @$_[$n .. $#$_] => returns_array_ref;

Or if you are working with a list:

    sub returns_list {1 .. 5}

    my @slice = sub {@_[$n .. $#_]}->(returns_list);
like image 32
Eric Strom Avatar answered Oct 15 '22 17:10

Eric Strom


I think mob's splice is the best option, but in the spirit of options:

my @result = reverse ((reverse 0..5)[0..$N+1]);

This returns the same result as the above example:

my @result = (0..5)[$N..5];
like image 35
mwp Avatar answered Oct 15 '22 17:10

mwp