获取 Perl 数组最后 N 个元素的最佳方法是什么?

发布于 2024-07-15 07:54:01 字数 86 浏览 4 评论 0原文

获取 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

猫瑾少女 2024-07-22 07:54:01
@last_n = @source[-$n..-1];

如果您不需要 undef,那么:

@last_n = ($n >= @source) ? @source : @source[-$n..-1];
@last_n = @source[-$n..-1];

If you require no undefs, then:

@last_n = ($n >= @source) ? @source : @source[-$n..-1];
帅气称霸 2024-07-22 07:54:01

我认为你想要的是 slice

I think what you want is called a slice.

涫野音 2024-07-22 07:54:01
@a = (a .. z);
@last_five = @a[ $#a - 4 .. $#a ];
say join " ", @last_five;

输出:

vwxyz

@a = (a .. z);
@last_five = @a[ $#a - 4 .. $#a ];
say join " ", @last_five;

outputs:

v w x y z

能否归途做我良人 2024-07-22 07:54:01

简单,无需数学:

@a = reverse @a;
@a = splice(@a, 0, $elements_to_keep);
@a = reverse @a;

simple, no math:

@a = reverse @a;
@a = splice(@a, 0, $elements_to_keep);
@a = reverse @a;
潜移默化 2024-07-22 07:54:01

由于标量上下文中的 @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.

心清如水 2024-07-22 07:54:01

TMTOWTDI,但我认为这更容易阅读(但从 @source 中删除元素):

my @last_n = splice(@source, -$n);

如果您不确定 @source 至少有 $n 元素:

my @last_n = ($n >= @source) ? @source : splice(@source, -$n);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文