Reputation: 86353
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.
Upvotes: 15
Views: 12735
Reputation: 1
I just use the array variable to get the len:
@a = (1,2,3,4,5);
print @a[1..@a];
# output: (2,3,4,5)
Upvotes: -1
Reputation: 8467
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];
Upvotes: 2
Reputation: 40152
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);
Upvotes: 1
Reputation: 118615
You can splice
it:
@result = splice @{[0..$M]}, $N; # return $N .. $M
Upvotes: 21