in reply to Re: Re: grep, map vs. foreach performance
in thread grep, map vs. foreach performance

Hi Django,

No, it is not a different thing. They are truly synonyms,
foreach($i=0; $i<$max; $i++){...};
is perfectly legal.

cheers

thinker.

Replies are listed 'Best First'.
Re^4: grep, map vs. foreach performance
by Flexx (Pilgrim) on Sep 04, 2002 at 13:04 UTC

    Ok, that's synonymous. Yet, unless I got something completely wrong (then please correct me), constructs like

    for($i=0; $i < @array; $i++){ print $array[$i]++ }; # Thanks for the dollar, jeffa ;)

    and
    foreach(@array){ print $_++;  };

    do something different internally. Of course, the second is generally the better/faster approach (unless you don't need $i for something else in the loop, since $i is an unnecessary artificial variable in the first example)).

    So long,
    Flexx

      It's really quite simple - for and foreach are the same. When you don't care about the value of the current index, don't use it:
      @array = ('a'..'z'); print $_,$/ for @array;
      When you do care about the value of the current index, do use it:
      printf "%02d: %s\n", $_+1, $array[$_] for 0..$#array;
      When in doubt, check with Deparse.pm:
      $ perl -MO=Deparse foo.pl @array = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); foreach $_ (@array) { print $_, $/; } foreach $_ (0 .. $#array) { printf "%02d: %s\n", $_ + 1, $array[$_]; } foo.pl syntax OK

      jeffa

      L-LL-L--L-LL-L--L-LL-L--
      -R--R-RR-R--R-RR-R--R-RR
      B--B--B--B--B--B--B--B--
      H---H---H---H---H---H---
      (the triplet paradiddle with high-hat)
      

        Hmm.. You missed my point (or you're repeating what I said). I wasn't comparing for(ARRAY) with for(TEMP_ARRAY), but for(ARRAY) with for(EXPR;EXPR;EXPR).

        I do know that for and foreach are synonymous words. I was trying to clarify that in

        for (@array) {$_++}

        $_ is an implicit alias for the current @array element. While in

        for (0 .. $#array) {$array[$_]++}

        $_ an alias for the current index. And that, in terms of what to use for what (as you already clarified) was the difference I meant...