http://qs1969.pair.com?node_id=561232

abachus has asked for the wisdom of the Perl Monks concerning the following question:

hello there, quick question if i may,

Whats the difference between :
for(@array){ print $_,"\n"; }
and...
foreach(@array){ print $_,"\n"; }
many thanks,

Isaac.

Replies are listed 'Best First'.
Re: for() or foreach() ?
by ikegami (Patriarch) on Jul 14, 2006 at 15:46 UTC

    Counting ("for") loops and iterating ("foreach") loops can use the for and the foreach keywords interchangably, as documented in perlsyn.

    Personally, I use "for" for counting ("for") loops, and "foreach" for iterating ("foreach") loops. Some people use "for" unconditionally because it is shorter.

    Iterating ("foreach") loops:

    foreach my $ele (@array) { ... } foreach (@array) { ... } ... foreach @array; foreach my $item ($list_item_0, $list_item_1, $list_item_2) { ... } foreach ($list_item_0, $list_item_1, $list_item_2) { ... } ... foreach $list_item_0, $list_item_1, $list_item_2;

    Also iterating ("foreach") loops:

    for my $ele (@array) { ... } for (@array) { ... } ... foreach @array; for my $item ($list_item_0, $list_item_1, $list_item_2) { ... } for ($list_item_0, $list_item_1, $list_item_2) { ... } ... foreach $list_item_0, $list_item_1, $list_item_2;

    Counting ("for") loops:

    for (my $i = 0; $i < 10; $i++) { ... } for my $i (0..9) { ... } # * for (0..9) { ... } # * ... for 0..9; # *

    Also counting ("for") loops:

    foreach (my $i = 0; $i < 10; $i++) { ... } foreach my $i (0..9) { ... } # * foreach (0..9) { ... } # * ... foreach 0..9; # *

    * — Loops of the form for/foreach [...] ($num1..$num2) are optimized into a counting ("for") loop.

      thanks folks, i've been using for() loops in place of foreach() for some time now, just wanted to be sure.

      Isaac.
Re: for() or foreach() ?
by polettix (Vicar) on Jul 14, 2006 at 15:31 UTC
    None, the two keywords are interchangeable.

    Flavio
    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Don't fool yourself.
Re: for() or foreach() ?
by wazzuteke (Hermit) on Jul 14, 2006 at 15:31 UTC
    Nothing... depending on the version of Perl you are running (I am assuming 5.8.x).

    I will say, however, foreach is getting dropped in Perl6 so it may be worth while to move to for rather than foreach

    ha||ta
Re: for() or foreach() ?
by kabeldag (Hermit) on Jul 14, 2006 at 17:10 UTC
    They are spelled differently. ;)