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

10,041

Solution 1

You can splice it:

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

Solution 2

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];

Solution 3

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);
Share:
10,041
thkala
Author by

thkala

A freelance Computer Engineer, with experience mainly on C, Java and all things Un*x...

Updated on July 02, 2022

Comments

  • thkala
    thkala almost 2 years

    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.

  • thkala
    thkala over 12 years
    Ah, this definitely works! I had tried splice but could not get it exactly right. +1
  • socket puppet
    socket puppet over 12 years
    This returns $N+1 items, but you want $#{anonymous_array}-$N items.