简体   繁体   English

如何在Perl中指定“尾部切片”?

[英]How to specify a “tail slice” in Perl?

If I want to extract only the 4th, 5th, and 7th elements (say) of tab-separated record, I can do something like: 如果我只想提取制表符分隔记录的第4,第5和第7个元素(比如说),我可以这样做:

my @f = (split(/\t/, $_, -1))[3, 4, 6];

But what if I want the 4th element and the "tail slice" consisting of all elements from the 7th one to the end of the array? 但是,如果我想要第4个元素和“尾片”,包括从第7个元素到数组末尾的所有元素,该怎么办? I don't know how to do this in a single line. 我不知道如何在一行中做到这一点。 The best I can do is this: 我能做的最好的就是:

my @f = split(/\t/, $_, -1);
@f = @f[3, 6..$#f];

The only reason for doing this operation in two lines is so that I can specify $#f in the second line, but this entails a greater degree of specificity than is inherent in the task; 在两行中执行此操作的唯一原因是我可以在第二行中指定$#f ,但这需要比任务中固有的更高程度的特异性; the task does not really care how many elements are in the value returned by split . 该任务并不关心 split返回的值中有多少元素。 It'd be nice to be able to specify something like "everything available from the 7th element onwards"... This is what I mean by a "tail slice": a slice where only the starting point is specified, while the end point is left implicit. 很高兴能够指定类似“从第7个元素开始可用的所有内容”......这就是我所说的“尾片”:只指定起点的切片,而终点是隐含的。

(This sort of specification is commonplace in uses of the cut utility in Unix; eg: (这种规范在Unix中使用cut实用程序时很常见;例如:

... | cut -f 4,7-

)

Is there some subscripting expression that I can apply directly to the (split(...)) subexpression to produce in one line the same effect as is achieved by the last two lines of code above? 是否有一些下标表达式,我可以直接应用于(split(...))子表达式,在一行中产生与上面两行代码所实现的效果相同的效果?

EDIT: To be clear, what I'm trying to avoid is the $#ARRAY construction. 编辑:要清楚,我要避免的是$#ARRAY构造。 I know that I can always do something like 我知道我总能做点什么

my @f = do { my @t = split(/\t/, $_, -1); @t[3, 6..$#t] };

The expression in the brackets of a list slice must return a list of zero or more indexes. 列表切片括号中的表达式必须返回零个或多个索引的列表。 So you'd have to know the number of items in the list being sliced before it's even produced. 因此,您必须知道在生成之前切片列表中的项目数。 So no, it can't be done using a list slice. 所以不,使用列表切片无法完成。

The most direct way of accessing a list on the stack is via @_ . 访问堆栈列表的最直接方法是通过@_ This does require a sub call, but it does give you an easy mechanism for leaving the list on the stack. 这确实需要一个子调用,但它确实为您提供了一种将列表留在堆栈上的简单机制。

my @f = sub { @_[6..$#_] }->( split(/\t/, $_, -1) );

Note that this solution does not create an array and copy the values into that array like the code in you've since added to your question. 请注意,此解决方案不会创建数组并将值复制到该数组中,就像您添加到问题中的代码一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM