获取 Perl 数组最后 N 个元素的最佳方法是什么?
获取 Perl 数组最后 N 个元素的最佳方法是什么?
如果数组少于 N,我不希望返回值中有一堆 undefs
。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您不需要
undef
,那么:If you require no
undef
s, then:我认为你想要的是 slice 。
I think what you want is called a slice.
输出:
outputs:
简单,无需数学:
simple, no math:
由于标量上下文中的 @a 给出数组 a 的长度,并且因为
@a == $#a + 1
(除非$[
设置为非零),可以通过@a[$n..@a-1]
-- #tmtowtdi 获取从第 $n 个(从零开始计数)到最后一个元素的切片。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.TMTOWTDI,但我认为这更容易阅读(但从
@source
中删除元素):如果您不确定
@source
至少有$n
元素:TMTOWTDI, but I think this is a bit easier to read (but removes the elements from
@source
):And if you are not sure that
@source
has at least$n
elements: