list 如何删除数组的前五个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5131144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:36:47  来源:igfitidea点击:

How do I remove the first five elements of an array?

arraysperllist

提问by nebulus

@array = qw(one two three four five six seven eight);
<Some command here>
print @array;

回答by friedo

Here are a few ways, in increasing order of dumbness:

这里有几种方法,按愚蠢程度递增:

Using a slice:

使用切片

@array = @array[ 5 .. $#array ];

Using splice:

使用splice

splice @array, 0, 5;

Using shift:

使用shift

shift @array for 1..5;

Using grep:

使用grep

my $cnt = 0;
@array = grep { ++$cnt > 5 } @array;

Using map:

使用map

my $cnt = 0;
@array = map { ++$cnt < 5 ? ( ) : $_ } @array;

I'm sure far better hackers than I can come up with even dumber ways. :)

我敢肯定,比我想出的更愚蠢的方法要好得多的黑客。:)

回答by Eric Strom

You are looking for the splicebuiltin:

您正在寻找splice内置:

splice @array, 0, 5;

回答by Anomie

splice @array, 0, 5;will do it.

splice @array, 0, 5;会做的。

回答by Joel Berger

As a comment to friedo's answer and to demonstrate cool new declaration state, here it is using grep, which friedo's mapemulates.

作为对 Friedo 的回答的评论并展示很酷的新声明state,这里使用的grep是 Friedo 的map模拟。

#!/usr/bin/perl

use strict;
use warnings;

use feature 'state';

my @array = qw(one two three four five six seven eight);

my @new_array = grep {state $count; ++$count > 5} @array;

print "$_\n" for @new_array; 

回答by cyber-guard

I just realized you only need the last string, so no need to loop

我刚刚意识到你只需要最后一个字符串,所以不需要循环

   my $_ = "@array"; s|(?:.*?\s){5}||;say;

Btw this is probably the least efficient way to do it, just having fun :)

顺便说一句,这可能是效率最低的方法,只是玩得开心:)