What's the best way to get the last N elements of a Perl array?
If the array has less than N, I don't want a bunch of undefs
in the return value.
What's the best way to get the last N elements of a Perl array?
If the array has less than N, I don't want a bunch of undefs
in the return value.
my $size = (scalar @list) - 1; my @newList = @list[$size-$n..$size];
@last_n = @source[-$n..-1];
If you require no undef
s, then:
@last_n = $n >= @source ? @source : @source[-$n..-1];
@a = (a .. z);
@last_five = @a[ $#a - 4 .. $#a ];
say join " ", @last_five;
outputs:
v w x y z