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

13,092

Solution 1

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.

Solution 2

I see these used interchangeably.

There is no difference other than that of syntax.

Solution 3

Four letters.

They're functionally identical, just spelled differently.

Solution 4

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.

Solution 5

From http://perldoc.perl.org/perlsyn.html#Foreach-Loops

The foreach keyword is actually a synonym for the for keyword, so you can use either. If VAR is omitted, $_ is set to each value.

# Perl's C-style
for (;;) {
    # do something
}

for my $j (@array) {
    print $j;
}

foreach my $j (@array) {
    print $j;
}

However:

If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.

Share:
13,092
planetp
Author by

planetp

I like the bytes burning under my fingers, the pixels fluorescing in the dark and the unlimited power of coding.

Updated on August 22, 2022

Comments

  • planetp
    planetp over 1 year

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