Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

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

by linuxer (Deacon)
on Apr 20, 2009 at 11:29 UTC ( #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.


Comment on Re: What’s the best way to get the last N elements of a Perl array?
Select or Download Code
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
Node Status?
node history
Node Type: note [id://758676]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (12)
As of 2014-12-27 16:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (177 votes), past polls