http://www.perlmonks.org?node_id=953

The foreach loop allows you to do something to each value in an array.
A quick example is below:

@numbers=(1,7,3,8,9); foreach $number(@numbers){ #makes $number point to array value; $number++; #$number is incremented by 1 which is refle +cted inside the actual array; } #Now if we print out all the numbers they should reflect our changes #ie @numbers is now equal to (2,8,4,9,10); foreach(@numbers){ #notice here we don't specify a variable so Perl us +es its default: [perlman:perlvar|$_] print "$_,"; #we print the changed numbers separated by commas }

Replies are listed 'Best First'.
Re: foreach loops
by mrbbking (Hermit) on Dec 16, 2001 at 01:08 UTC
    In the last example, where foreach uses the default $_, you could go one step further and allow print to do the same.
    If you're willing to forego the commas, that is:
    foreach(@numbers){ print; }
      You can keep the commas and forgo the loop if you want...
      local $, = ","; print @numbers;
      Or keep the comma with:
      foreach(@numbers) { local $\ = ','; print; }

      -Blake

        Really i am enjoying doing perl ,as perlmonks are with me. Thanks! for this work.
Re: foreach loops
by Bilbo (Pilgrim) on May 27, 2002 at 13:51 UTC
    I think that it would be useful to point out that the loop variable is aliased to each element of the array in turn. It is not a copy of the element, so modifying the loop variable will modify the original array. One simple application of this is the initialisation of an array.
    # Initialise an array so that $array[n] = n my $n = 0; foreach (@array) {$_ = $n++}
      # Initialise an array so that $array[n] = n my $n = 0; foreach (@array) {$_ = $n++}
      Your code is overwriting the contents of an already existing array, I wouldn't call that initialising ...

      Putting that aside, an array slice is a good way to do that task without using a loop.

      @array[0..100] = 0..100; # or to mimic the behaviour of your code exactly @array[0..$#array] = 0..$#array;

      -- Hofmator

        Thank you - I've suddenly understood what array slices are for and how useful they are (I haven't been learning Perl for very long - I've certainly got a long way to go). I admit that I didn't choose a very good example. I think that my main point is still relevant though.
      No one's reading this, but thanks Bilbo. Super help on a problemo I've been having - I think I think too much about the problems I have.
Re: foreach loops
by Mr. Muskrat (Canon) on Dec 22, 2004 at 06:30 UTC

    Something that has not been mentioned in this thread or in for loops is the reversed form of the for/foreach loop.

    my %hash; my @array = qw( ABC DEF GHI ); $hash{$_}++ for (@array); # $_ is the loop variable.
    This code is no different than the following except that the for comes at the end (and that you are forced to use $_ as the loop variable).
    my %hash; my @array = qw( ABC DEF GHI ); for my $key (@array) { $hash{$key}++ }
Re: foreach loops
by Anonymous Monk on Jun 28, 2001 at 18:40 UTC
    Simple and helpful. ^_^
    I'll be using this a lot more often now.
Re: foreach loops
by Anonymous Monk on Nov 06, 2001 at 08:08 UTC
    new kind of loop that i've learned...very helpful. :)
Re: foreach loops
by jamgill (Acolyte) on Oct 08, 2003 at 19:15 UTC
    what if the array is a matrix (array of arrays)? How do ya make the loop operate on just the row in the matrix (or the inner level of array, if that is a better way to say it)? thanks...
Re: foreach loops
by zemote (Scribe) on Feb 20, 2003 at 15:07 UTC
    This is gonna make my life much easier. zemote
RE: foreach loops
by Anonymous Monk on May 24, 2000 at 05:37 UTC
    Great Tutorial! A link back to the main page here would be nice...
Re: foreach loops
by @rocks (Scribe) on Oct 30, 2002 at 21:50 UTC
    Love the tutorial. I read about foreach about 2 weeks ago in a book about Perl that I had bought but didn't understand it. I thought oh well I will never need this, but I soon realized I really need something that can do something to all variables in an array(@) in one command structure. I read this tutorial and tried it. It worked perfectly! Thank you for writing this tutorial and making it easy to understand and find, bravo!

    -@rocks

incorrect output
by Anonymous Monk on Feb 05, 2005 at 12:53 UTC
    @a={1,2,3,4,5};
    foreach $no (@a)
    {
    print "$no,";
    }
    OUTPUT :HASH(0x92efd28),
      That's the correct output. You may be misunderstanding this line:
      @a = {1, 2, 3, 4, 5};
      This line creates an anonymous hash by taking pairs of elements to create individual hash elements. With warnings enabled, you'd have also have been notified that the element "5" has no pair to take with it, so the hash is also improperly specified. Then the reference to this new anonymous hash becomes the sole element of the array @a.

      Perhaps you wanted:

      @a = (1, 2, 3, 4, 5);

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

      u have to initialize as
      @a=(1,2,3,4,5)
      or each element within double quotes