tags:

views:

270

answers:

5

I see these used interchangeably. What's the difference?

+11  A: 

I see these used interchangeably.

There is no difference other than that of syntax.

Sarfraz
+1 Yes, Perl is quite rich in syntactic sugar. There Is More Then One Way to Say It.
Thilo
@Thilo: agreed :)
Sarfraz
@Sinan Ünür: Thanks :)
Sarfraz
+18  A: 

There is no difference. From perldoc perlsyn:

The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.

Hans W
+5  A: 

Four letters.

They're functionally identical, just spelled differently.

Dave Sherohman
Actually the compile down to the same opcodes. So for all intents and purposes, they are identical.
Brad Gilbert
+2  A: 

Ever since its introduction in perl-2.0, foreach has been synonymous with for. It's a nod to the C shell's foreach command.

In my own code, in the rare case that I'm using a C-style for-loop, I write

for (my $i = 0; $i < $n; ++$i)

but for iterating over an array, I spell out

foreach my $x (@a)

I find that it reads better in my head that way.

Greg Bacon
I find the opposite: I always use `for my $x (@a)`. I prefer Python's `for x in a` loops, or maybe even PHP's `for(@a as $x)`. I never use C-style `for` loops. I'd write what you have as `for my $i (0 .. $n)`. Perl special-case optimizes that not to create an unnecessary list, so the difference between it and your explicit C-style `for` loop should be negligible, and I think it's more readable that way.
Chris Lutz
+1  A: 

Dear Friend,

In case of the "for" you can use the three steps.

1) Initialization 2) Condition Checking 3) Increment or decrement

But in case of "foreach" you are not able increment or decrement the value. It always take the increment value as 1.

muruga