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";
}
Share:
11,184
tukaef
Author by

tukaef

Updated on June 08, 2022

Comments

  • tukaef
    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
    ikegami over 11 years
    And of course, there's for (1..$#arr) { ... $arr[$_] ... } (which uses O(1) memory instead of O(N))
  • TLP
    TLP over 11 years
    Yes, there are many ways to do it. I opted for one of them, though I could have shown all of them.
  • Demnogonis
    Demnogonis over 11 years
    Not exactly the same. for provides the current array index in $_. foreach provides the current element.
  • Borodin
    Borodin over 11 years
    @Demnogonis: That is not true. for and foreach are identical in Perl
  • Demnogonis
    Demnogonis over 11 years
    @Borodin: Dang, you're right. I thought it worked that way... Sorry for telling guff.
  • TLP
    TLP over 11 years
    @Demnogonis The foreach keyword is actually a synonym for the for keyword, so you can use either. Quote from perldoc perlsyn.