What's the difference between 'for' and 'foreach' in Perl?

Viewed 13705

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

8 Answers

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.

I see these used interchangeably.

There is no difference other than that of syntax.

Four letters.

They're functionally identical, just spelled differently.

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.

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.

Related