Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

difference between for and foreach?

by john1987 (Acolyte)
on Jan 20, 2001 at 19:30 UTC ( #53214=perlquestion: print w/replies, xml ) Need Help??

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

does anyone know the difference between the for and the foreach statements?

Replies are listed 'Best First'.
Re: difference between for and foreach?
by merlyn (Sage) on Jan 20, 2001 at 23:12 UTC
    The words for and foreach are interchangable, syntactically. (This is what most people are saying when they say there's "no difference").

    However, as Larry intended it, there's a "for" statement, with 3 parts, like C's same-named, and a "foreach" statement, like csh's same-named loop. And they do nicely different things, even though they're both basically loops.

    So, yes, there's a difference, except when there's not a difference. If you check the Llama, we're very careful to describe the two kinds of loops seperately. They have different uses and syntax.

    -- Randal L. Schwartz, Perl hacker

(kudra) Re: difference between for and foreach?
by kudra (Vicar) on Jan 20, 2001 at 19:52 UTC
    In Perl, for and foreach can be used interchangably.

    In the future, you might try seeing if the question has already been addressed by using 'search'. For example, this question was answered here, which I found by simply putting 'for foreach' in the search box.

Re: difference between for and foreach? (..the stench and the peril)
by turnstep (Parson) on Jan 20, 2001 at 21:09 UTC

    Argh! There is no difference between "for" and "foreach." I write a lot of perl, and have never used "foreach". Why? Because "for" is less typing :). It's sheerly a stylistic thing. Here's the proof, direct from the perl source code:

    case KEY_for: case KEY_foreach:
    If you grok C, you'll realize that "for" falls through to the next case statement, the "foreach". Hence, no difference, except for the extra typing. Think of all the wear and tear saved on your keyboard over the years. ;)

For and foreach...
by Elgon (Curate) on Jan 20, 2001 at 20:14 UTC
    Perl has these two statements for a reason and they are appropriate each in different cases. When I first learned how to use foreach I was astounded how groovy and useful it can be.

    The for command is great for performing a single series of mathematical calculations on a continous and possibly contiguous list of numbers, for example. I don't use it a great deal because what you used to do in BASIC with ...

    for i = 1 to 10 myarray(i) = myarray(i) + 1 next i

    Or equivalently in Perl...

    my $i; my @array = (1, 5, 6, 9, 57); for ($i=0; $i <= (scalar(@array)-1); ++$i) { ++$array[$i]; } done far more easily (and efficiently?) with foreach.

    foreach $bar(@bar) { ++$bar; }

    Basically, foreach allows you to act over a data structure and perform a function efficiently, whereas for allow you to work over a fixed range of numbers with a function (and then presumably do something with the result) or perform a function a given number of times.

    Okay, now for the lecture part: Finding this sort of information isn't too difficult, a good start would have been typing 'For loops' and 'Foreach loops' in the search box at the top left of most/all pages on Perlmonks. Don't sweat it, we've all done it at some point and I doubt anyone here will flame you to a crisp but try and give it a go yourself first, play with Perl. Ideally if you are having problems make the title descriptive and then post some example code (inside <code> </code> tags to make it purty) and ask for help: we promise we won't laugh, at least they haven't laughed at me yet!

    See this tutorial and this tutorial for help.


    Update: In response to enlightened posters such as salvadors and turnstep, I am aware of Perl's ability to do 'the right thing' and the fact that in many ways for and foreach are identical, however in it is easier to read and therefore generally 'better style' to use these two commands appropriately. The `efficiently?` comment should be read in backticks to invite answers by people who know more about how Perl works at the lower levels than me.

    On a final note, thankyou to merlyn for explaining what I was trying to get across, only better.

      Perl has these two statements for a reason and they are appropriate each in different cases ... is done far more easily (and efficiently?) with foreach.

      No, no, no. For and foreach are identical. Yes, they're there for a reason, but that's not because they do anything different, or because one is better at one thing, or anything like that.

      Perl as a language grew out of linguistic principles. Larry describes Perl as a diagonal language rather than an orthogonal one. It has no problem having more than one command that does exactly the same thing, just as most natural languages have words that mean exactly the same thing. The two different versions of for make it easier to read Perl in English.

      You can quite happily, to take your examples, write:

      foreach ($i=0; $i <= (scalar(@array)-1); ++$i) { ++$array[$i]; }
      for $bar (@bar) { ++$bar; }
      and perl will Do The Right Thing(tm). In fact it will Do The Same Thing. But many people will find it easier to read them the original way. Which is important in the Perl World.


        and don't forget:
        for my $i (0..$#array) { ++$array[$i]; }
        for those times when you need the index
        much cleaner than doing it C-style.


        (the triplet paradiddle)
Re: difference between for and foreach?
by Anonymous Monk on Jan 20, 2001 at 21:33 UTC
    > does anyone know the difference between the
    > for and the foreach statements?

    About 4 characters. rimshot

    Otherwise, absolutely nothing.

Re: difference between for and foreach?
by monk2b (Pilgrim) on Jan 20, 2001 at 19:50 UTC
    For allows you to do something a certain number of times
    Foreach allows you to do something to each value
    learning too

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2022-07-01 19:30 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (102 votes). Check out past polls.