in reply to Re^2: Closures & aliases
in thread Closures & aliases

A for loop and a foreach loop are slightly different. Adding to the confusion is that for and foreach are synonyms for each other (no pun intended).
for my $y ( @a ) {...}
makes $y an alias for one element of @a each time through the loop. Writing
foreach my $y ( @a ) {...}
is identical, but 4 chars longer to type.

On the other hand,

foreach ( $x=0; $x < $#a; $x++ ) {my $y=$a[$x];...}
would behave similarly, except $y is not an alias for elements of @a, but a copy. And using
for ( $x=0; $x < $#a; $x++ ) {my $y=$a[$x];...}
would not change the behavior here either.

Which form the compiler chooses is based on the argument list to for/foreach, and not the name itself!

I hope that helps :|

Update: I wish I'd have said it more like hv did below. Maybe he'll volunteer to edit for me in the future ;)

A for loop and a foreach loop are slightly different.
I attempted (but failed) to say that the OP seemed to understand them as different entities. The only difference is what follows the keyword, and not the keyword itself.

-QM
--
Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re^4: Closures & aliases
by hv (Prior) on Jun 06, 2004 at 04:05 UTC
    A for loop and a foreach loop are slightly different.

    No, they are synonyms, and therefore identical.

    Adding to the confusion is that for and foreach are synonyms for each other

    Yes, they are synonyms, and therefore identical.

    for and foreach are synonyms. They are therefore identical. However they are used (interchangeably) to introduce two completely different types of loop, the "C-style for loop":

    LABEL for (EXPR; EXPR; EXPR) BLOCK
    and another one for which I know no convenient name (the "list-style for loop"?):
    LABEL for VAR (LIST) BLOCK

    It is unfortunate that the presentation of these two loop styles in perlsyn implies that the keyword for the first is "for" and for the second is "foreach", since that isn't true: the two are synonyms, hence interchangeable.

    Hope this helps. :)

    (no pun intended).

    None implied.

    Hugo