Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip first element in array with foreach?

Say I have an array:

my @arr = (1,2,3,4,5);

Now I can iterate it via foreach:

foreach ( @arr ) {
    print $_;
}

But is there a way to iterate from second (for example) to last elemnt?

Thanks in advance.

like image 587
tukaef Avatar asked Dec 22 '12 19:12

tukaef


People also ask

How do you skip the first element of an array?

The shift() method removes the first element from an array and returns that removed element.

Can you use break with forEach?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

How do I remove the first element?

The shift() method removes the first item of an array. The shift() method changes the original array.


2 Answers

Just shift off the first element before you go looping.

my @arr = ( 1..5 );
shift @arr; # Remove the first element and throw it away

foreach ( @arr ) {
    print "$_\n";
}
like image 115
Andy Lester Avatar answered Sep 16 '22 18:09

Andy Lester


This is perl. There are more than one way to do it, always. Such as an array slice:

for (@arr[1 .. $#arr])   # for and foreach are exactly the same in perl

You can use shift as Andy Lester suggested, however this will of course alter your original array.

like image 35
TLP Avatar answered Sep 16 '22 18:09

TLP