What's the best way to get the last N elements

2019-02-06 00:22发布

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.

6条回答
▲ chillily
2楼-- · 2019-02-06 00:52
@last_n = @source[-$n..-1];

If you require no undefs, then:

@last_n = ($n >= @source) ? @source : @source[-$n..-1];
查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-06 00:58

simple, no math:

@a = reverse @a;
@a = splice(@a, 0, $elements_to_keep);
@a = reverse @a;
查看更多
冷血范
4楼-- · 2019-02-06 00:58

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);
查看更多
狗以群分
5楼-- · 2019-02-06 01:00
@a = (a .. z);
@last_five = @a[ $#a - 4 .. $#a ];
say join " ", @last_five;

outputs:

v w x y z

查看更多
疯言疯语
6楼-- · 2019-02-06 01:00

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.

查看更多
Root(大扎)
7楼-- · 2019-02-06 01:04

I think what you want is called a slice.

查看更多
登录 后发表回答