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.
The shift() method removes the first element from an array and returns that removed element.
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.
The shift() method removes the first item of an array. The shift() method changes the original array.
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";
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With