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.
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.
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.
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.
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.
You can splice
it:
@result = splice @{[0..$M]}, $N; # return $N .. $M
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);
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];
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