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 |