Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Re: grep, map vs. foreach performance

by Django (Pilgrim)
on Sep 04, 2002 at 10:03 UTC ( [id://195024]=note: print w/replies, xml ) Need Help??


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

"for" can be used as a synonym for "foreach", but what about something like "for ($i=0; $i<$max; $i++) {}"? That's a completely different thing, isn't it?

~Django
"Why don't we ever challenge the spherical earth theory?"

Replies are listed 'Best First'.
Re: Re: Re: grep, map vs. foreach performance
by thinker (Parson) on Sep 04, 2002 at 10:09 UTC
    Hi Django,

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

    cheers

    thinker.

      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)
        

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://195024]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (1)
As of 2024-04-25 01:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found