Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all except the first one in an array

Tags:

arrays

perl

I want to slice an array to create a new array containing all but the first entry in the array. This is what i tried:

@arguments = $splittedCommands[1..-1];  

Which gives me an empty result. 1 should be the second entry and -1 should be the last, so why doesn't this work?

like image 722
Luke Avatar asked Dec 02 '25 09:12

Luke


2 Answers

You should use @ in front of array when slicing an array ($ tells that your're accessing single scalar value inside array), so

my @arguments = @splittedCommands[ 1 .. $#splittedCommands ];

Second, your range should be either -$#splittedCommands .. -1 or 1 .. $#splittedCommands with later being more common and straightforward.

like image 172
mpapec Avatar answered Dec 04 '25 21:12

mpapec


Easiest may be to assign it into another list, using

( undef, my @commands ) = @splittedCommands;

Assigning into undef here throws away the first result, then the remainder goes into @commands

Another approach could be to assign the lot and then remove the first

my @commands = @splittedCommands;
shift @commands;

This could also be simplified if you didn't need to keep the original array around any more; just shift the first item off @splittedCommands then use it directly.

like image 36
LeoNerd Avatar answered Dec 04 '25 22:12

LeoNerd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!