Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

list

perl

@array = qw(one two three four five six seven eight);
<Some command here>
print @array;
like image 925
masterial Avatar asked Feb 27 '11 02:02

masterial


3 Answers

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

like image 66
friedo Avatar answered Nov 14 '22 03:11

friedo


You are looking for the splice builtin:

splice @array, 0, 5;
like image 21
Eric Strom Avatar answered Nov 14 '22 03:11

Eric Strom


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

like image 26
Anomie Avatar answered Nov 14 '22 04:11

Anomie