如何从匿名 Perl 数组中获取从索引 N 到末尾的所有元素?
在 Perl 5 中,当我们有一个命名数组时,例如 @a
,从索引 $N
开始获取元素非常简单,只需使用一点 切片:
my @result = @a[$N..$#a];
是否有一种标准方法可以对匿名数组执行相同的操作,而无需显式提供长度?即,可以将 this:
my @result = (0,1,2,3,4,5)[2..5];
或者更具体地说,将 this:
my @result = (0,1,2,3,4,5)[$N..5];
转换为不需要明确范围上限的内容吗?也许是一些晦涩难懂的 Perl 语法?也许可以切块而不是切片?
PS:我已经将其编写为一个函数 - 我正在寻找一种更独立的方法。
In Perl 5, when we have a named array, e.g. @a
, getting the elements from index $N
onwards is simple with a bit of slicing:
my @result = @a[$N..$#a];
Is there a standard way to do the same with an anonymous array, without having to supply the length explicitly? I.e. can this:
my @result = (0,1,2,3,4,5)[2..5];
or, more specifically, this:
my @result = (0,1,2,3,4,5)[$N..5];
be converted to something that does not need the upper range limit to be explicit? Perhaps some obscure Perl syntax? Maybe a bit of dicing instead of slicing?
PS: I have already written this as a function - I am looking for a more self-contained approach.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以
拼接
它:You can
splice
it:我认为 mob 的 splice 是最好的选择,但本着选项的精神:
这返回与上面示例相同的结果:
I think mob's
splice
is the best option, but in the spirit of options:This returns the same result as the above example:
如果将数组引用设置为主题,则不需要为数组引用指定名称:
或者如果您正在使用列表:
You don't need to give an array ref a name if you set it as the topic:
Or if you are working with a list:
我只是使用数组变量来获取 len:
I just use the array variable to get the len: