Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

for vs foreach

by vkonovalov (Monk)
on Jul 14, 2000 at 13:41 UTC ( [id://22524]=perlquestion: print w/replies, xml ) Need Help??

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

I often use for and never use foreach.
Does anyone knows how they differ? Any examples of different behaviour?
Rough browsing through perl source code makes me think that they slightly differ, but how?

Thanks.

Replies are listed 'Best First'.
Re: for vs foreach
by mikfire (Deacon) on Jul 14, 2000 at 15:30 UTC
    And I quote from perlsyn
      The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for
      brevity. (Or because the Bourne shell is more familiar to you than csh, so writing for comes more naturally.) If VAR is
      omitted, $_ is set to each value. If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop.
      That's because the foreach loop index variable is an implicit alias for each item in the list that you're looping over. 
    

    mikfire

Re: for vs foreach
by davorg (Chancellor) on Jul 14, 2000 at 13:55 UTC

    I'm the complete opposite. I can't remember the last time that I used for. It always seems to me that for iteraring over a list, the foreach syntax is more natural. I find

    foreach (@array) { # do someting with $_ }

    far easier to follow than

    for ($i = 0; $i < @array; ++$i) { # do something with $array[$i] }

    If, for some reason you need the array index for some calculation, then you can use

    foreach $i (0 .. $#array) { # do something with $array[$i] }

    Of course, if you're really keen on saving keystrokes you can always spell foreach as for.

    --
    <http://www.dave.org.uk>

    European Perl Conference - Sept 22/24 2000, ICA, London
    <http://www.yapc.org/Europe/>
      for me
      for (@array) { # do someting with $_ }
      is quite natural, and
      for my $i (0..$#array) {...
      is used quite often by me...

      I'm still searching for perl wisdom to find different behaviour between for and foreach

Re: for vs foreach
by c-era (Curate) on Jul 14, 2000 at 14:58 UTC
    This is my thoughts. In perl 4 for and foreach had different syntax. For was like its C counter part, and foreach had the form you are using. In perl 5 these two became interchangeable. There is a good posibilty that they are now the same code with different names for backward compatability. That is my thoughts on the subject. If anyone has found any documentation that would be great.
      The words for and foreach have always been interchangable back to Perl version 0.

      But for purposes of documentation, we call a for loop the thing that acts very C-like (with three expressions separated by semicolons), and foreach is reserved for the csh-like thing (with a variable to walk through a list).

      In my experience, people start out writing a lot of for-loops, but end up writing many more foreach loops. Of course, people spell it "f-o-r" and pronounce it "foreach".

      -- Randal L. Schwartz, Perl hacker

        Thanks for the info. I probably didn't realize they were then same until perl 5 came out.
Re: for vs foreach
by Macphisto (Hermit) on Jul 14, 2000 at 17:47 UTC
    Well, I'm getting roasted...so bye bye answer!!! Whats the reason for the - votes? What did I have/do wrong? The beatings will continue until morale raises.
      See the comments above, your statement is incorrect. for can just as easily iterate over a list as foreach (without an explicit iterator), they are completly interchangeable.
      @a = ( 1, 2, 3, 4); for(@a) { print; } print "\n"; foreach(@a) { print; } print "\n"; for($i=0; $i<@a; $i++) { print @a[$i]; } print "\n"; foreach($i=0; $i<@a; $i++) { print @a[$i]; } print "\n";
      Results:
      1234 1234 1234 1234
      Macphisto, I didn't see your original post, but it sounds as if you simply posted something incorrect. That doesn't excuse any -- votes (and I'm giving you ++, because a wrong answer does not deserve a vote-down in SoPW).

      However, let me encourage you not to simply remove your original post. There is a much better chance for others to learn something if you will just modify your post by adding an update tag, like:
      Update: LSD flashbacks caused me to confuse valid Perl code with Mork and Mindy's home phone number. Here is what I should have said...

      That way, you can avoid negative votes (which, again, should not happen simply for incorrect posts) for your original post, and even more negative votes for a "deleted" post.

      Thanks for posting, and welcome to our community.

      Russ
      Brainbench 'Most Valuable Professional' for Perl

        Thanks, Russ. I appreciate the open mind. I got blasted for that post. I didn't check my code and paid for it! Ouch! The beatings will continue until morale raises.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (9)
As of 2024-04-23 13:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found