问题
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.
回答1:
@last_n = @source[-$n..-1];
If you require no undef
s, then:
@last_n = ($n >= @source) ? @source : @source[-$n..-1];
回答2:
I think what you want is called a slice.
回答3:
@a = (a .. z);
@last_five = @a[ $#a - 4 .. $#a ];
say join " ", @last_five;
outputs:
v w x y z
回答4:
simple, no math:
@a = reverse @a;
@a = splice(@a, 0, $elements_to_keep);
@a = reverse @a;
回答5:
As @a in scalar context gives the length on an array a and because @a == $#a + 1
(unless $[
is set to non-zero), one can get the slice from the $nth (counting from zero) to to last element by @a[$n..@a-1]
-- #tmtowtdi.
回答6:
TMTOWTDI, but I think this is a bit easier to read (but removes the elements from @source
):
my @last_n = splice(@source, -$n);
And if you are not sure that @source
has at least $n
elements:
my @last_n = ($n >= @source) ? @source : splice(@source, -$n);
来源:https://stackoverflow.com/questions/611723/whats-the-best-way-to-get-the-last-n-elements-of-a-perl-array