What's the best way to get the last N elements of a Perl array?

时光总嘲笑我的痴心妄想 提交于 2019-12-30 02:43:09

问题


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 undefs, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!