Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: What’s the best way to get the last N elements of a Perl array?

by linuxer (Curate)
on Apr 20, 2009 at 11:29 UTC ( [id://758676]=note: print w/replies, xml ) Need Help??


in reply to What’s the best way to get the last N elements of a Perl array?

If undef is no valid entry in your array, you could use your solution and grep the defined values from your slice result.

@last_n = grep { defined $_ } @source[ -$n .. -1 ];

Update:

As svenXY mentioned: my solution does not work! :o(

$ perl -wle '@a = 1..3; @b = grep { defined $_ } @a[-4 .. -1]; print " +<$_>" for @b;' Modification of non-creatable array value attempted, subscript -4 at - +e line 1. $ perl -wle '@a = 1..3; @b = @a[-4 .. -1]; @b = grep {defined $_} @b; +print "<$_>" for @b;' <1> <2> <3>

Can someone please enlighten me, what's the problem with my attempt?

2nd Update:

During my research I found an explanation in Modification of non-creatable array value attempted (it's a slightly other topic, but at least the same error message) and grep's perldoc.

I came to the conclusion, that the error is thrown, because grep tries to alias the list values; and this fails for not existent array elements.

Replies are listed 'Best First'.
Re^2: What’s the best way to get the last N elements of a Perl array?
by svenXY (Deacon) on Apr 20, 2009 at 11:40 UTC
    nope, does not work for me: Modification of non-creatable array value attempted, subscript -9 at array_ende.pl line 23. whereas it does work as a two-liner (see above)
    Regards,
    svenXY

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://758676]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-25 05:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found