mattford63 has asked for the wisdom of the Perl Monks concerning the following question:
However, "for" is not always a synonym for "foreach". Care must be used if one is to say it's a "misspelling" or they can be used "interchangeably". "For" looks to behave differently depending on it's context: c-style vs. (er) foreach-style. If one uses c-style "for" loops you don't always get localised indexing variables as you seem to in "foreach" loops.
UPDATE: the above paragraph is wrong - "for" and "foreach" can be used interchangeably. The key point for me is that "for" is overloaded and behaves differently depending on the form of the arguments. ikegami's response sums it all up nicely in my opinion. Ironically "foreach" which is supposed to (and does) aid the programmer by letting him know explicitly what form of "for" is being used, tricked me into thinking about it in a weird way.
Anyhow, I'm interested in why Perl has the two styles of "for" constructs: convenience to the programmer seems the likely answer? I certainly appreciate the "foreach" loop. I'm assuming the "foreach" loop came after the "c-style for" loop - is this the correct Perl history? And if so, why was "foreach" implemented in a way such that the indexing variable is localised. Was this an ease of implementation decision or something else?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: For vs. Foreach
by ikegami (Patriarch) on Feb 13, 2009 at 17:56 UTC | |
by Eimi Metamorphoumai (Deacon) on Feb 13, 2009 at 18:25 UTC | |
by ikegami (Patriarch) on Feb 13, 2009 at 19:04 UTC | |
by ack (Deacon) on Feb 13, 2009 at 19:16 UTC | |
by merlyn (Sage) on Feb 13, 2009 at 21:58 UTC | |
by BrowserUk (Patriarch) on Feb 14, 2009 at 04:01 UTC | |
| |
by ikegami (Patriarch) on Feb 14, 2009 at 03:19 UTC | |
by Anonymous Monk on Feb 14, 2009 at 01:27 UTC | |
Re: For vs. Foreach
by moritz (Cardinal) on Feb 13, 2009 at 17:48 UTC | |
Re: For vs. Foreach
by Joost (Canon) on Feb 13, 2009 at 17:45 UTC | |
Re: For vs. Foreach
by tilly (Archbishop) on Feb 13, 2009 at 17:28 UTC | |
by JavaFan (Canon) on Feb 13, 2009 at 18:04 UTC | |
by tilly (Archbishop) on Feb 13, 2009 at 19:49 UTC |