>>>>> ""sanket" == "sanket vaidya" <sanket.vai...@patni.com> writes:

"sanket> What is the difference between the 'for' & 'foreach' loops? I know 
that they
"sanket> can be used interchangeably then what is the purpose of keeping them
"sanket> separate? Can anyone suggest me a good url which can tell the 
difference
"sanket> between two?


Back in the early days of Perl, Larry Wall decided to borrow from both C (the
"for" loop) and Csh (the "foreach" loop) to provide a means of a computed
iterator or a simple list enumeration.

Apparently, he noticed that Perl could always distinguish (by the contents of
the parentheses part of the statement) whether a for-loop or a foreach-loop
was needed, Larry decided to make the keywords interchangable, simply
because they were both "iterators" and the more common of the two loops
(the foreach loop) could be spelled with 4 fewer characters.

In the early documentation (the first Camel which I wrote with Larry, and the
first Llama), we were very careful to describe the aliasing of the keyword,
but *also* very careful to always use the proper keyword for the loop type in
every example, just to make sure it was clear to the early Perl users that
these really are two distinct types of loop.

Later documentation that has come along (*not* written by me or Larry) has
more sloppily merged the two, and made it more confusing, I think.  I can
predict followups to my message here that argue the opposite of what i'm
saying.  Rest assured, *they* were *not* there in the beginning, nor have had
as much time sitting across the dinner table with Larry himself as I have had,
so I speak from authority on this matter.

To summarize:  the "for" loop is from C, and looks like:

  for (initializer; test; incrementor) { body }

The "foreach" loop is from csh, and looks like:

  foreach $optional_iterator (list) { body }

However, you can spell "for" as "foreach" and vice versa, and Perl
won't care... it'll correct for your misspelling. :)

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<mer...@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.vox.com/ for Smalltalk and Seaside discussion

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to