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]; }
and
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.

Tony


In reply to Re: For and foreach... by salvadors
in thread difference between for and foreach? by john1987

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.