How to skip first element in array with foreach?
11,184
Solution 1
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.
Solution 2
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";
}
Author by
tukaef
Updated on June 08, 2022Comments
-
tukaef almost 2 years
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.
-
ikegami over 11 yearsAnd of course, there's
for (1..$#arr) { ... $arr[$_] ... }
(which uses O(1) memory instead of O(N)) -
TLP over 11 yearsYes, there are many ways to do it. I opted for one of them, though I could have shown all of them.
-
Demnogonis over 11 yearsNot exactly the same.
for
provides the current array index in$_
.foreach
provides the current element. -
Borodin over 11 years@Demnogonis: That is not true.
for
andforeach
are identical in Perl -
Demnogonis over 11 years@Borodin: Dang, you're right. I thought it worked that way... Sorry for telling guff.
-
TLP over 11 years@Demnogonis
The foreach keyword is actually a synonym for the for keyword, so you can use either.
Quote fromperldoc perlsyn
.