The perlsyn doc says that "foreach" is a synonym for "for", so the two are indeed interchangable. But you should also note that there are 2 different "modes" in which the for/foreach statement works.
If you use it in the C-style "for($x=1; $x<10; $x++) {}" way, then $x is not localized to the loop (unless you declare it with "my" as part of the for() loop). Use this mode if you want to modify $x within the loop and have the value of $x persist even after the loop exits. $x = "hello"; foreach ($x=1; $x < 5; $x++) { print "x = $x\n"; } print "done. x = $x\n"; Results in: x = 1 x = 2 x = 3 x = 4 done. x = 5 The other mode is the more foreach-ish one... "foreach $x (1 .. 10) {}". The difference here is that the value of $x is localized (ie. hidden away and then restored when the loop exits) implicitly. For example: my $x = "hello"; for $x (1 .. 5) { print "x = $x \n"; } print "done. x = $x\n"; Results in: x = 1 x = 2 x = 3 x = 4 x = 5 done. x = hello I'm not sure why they didn't just keep them separate because, to me, it makes things more confusing since most people are used to seeing "for" used in the C-style way and "foreach" used in the C-shell-style way, not vice-versa (as I just did). The localization feature is nice but it certainly makes perl seem hard for beginners. -- Brad > On Fri, 2002-03-01 at 14:52, James Taylor wrote: > > I'm really curious what the point of foreach is considering for does the same > > exact thing? For example: > > > > @myarray = (1 .. 10); > > > > for (@myarray) { > > print "$_\n"; > > } > > > > > > Or, you could swap the for for a foreach and the same thing would get > > accomplished... The only difference I can think of is a slightly different > > handling of hashes. Is this the only benefit of foreach? What am I missing > > here > > It is my understanding that for and foreach were once different, but now > the same. Which would mean that foreach is still here for backward > compatibility and style reasons. > > -- > Today is Setting Orange the 60th day of Chaos in the YOLD 3168 > Hail Eris! > > Missile Address: 33:48:3.521N 84:23:34.786W > > > -- > To unsubscribe, e-mail: [EMAIL PROTECTED] > For additional commands, e-mail: [EMAIL PROTECTED] > -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]