开发者

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

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


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

Using a slice:

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

Using splice:

splice @array, 0, 5;

Using shift:

shift @array for 1..5;

Using grep:

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

Using map:

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

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


You are looking for the splice builtin:

splice @array, 0, 5;


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


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

#!/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; 


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜