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

In Perl 5, when we have a named array, for example. @a , getting elements from index $N forward just with a bit of slicing :

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

Is there a standard way to do the same with an anonymous array without specifying the length explicitly? That is, it can:

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

or, more specifically, it:

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

converts to something that does not require a limit to the upper limit of the range? Perhaps some obscure Perl syntax? Maybe a little chop, not chop?

PS: I already wrote this as a function - I'm looking for a more independent approach.

+8
arrays perl
source share
3 answers

You can splice it:

 @result = splice @{[0..$M]}, $N; # return $N .. $M 
+17
source share

I think mob 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 previous example:

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

You do not need to specify a ref name array if you set it as a theme:

     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);
+1
source share

All Articles