http://www.perlmonks.org?node_id=341179


in reply to Re: Lexicals in if() scope gotcha!
in thread Lexicals in if() scope gotcha!

So for and foreach are not just aliases for each other, as I've seen elsewhere.

Update: So they are aliases, but there are still 2 entities, and the entity chosen depends on context.

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

Replies are listed 'Best First'.
•Re: Re: Re: Lexicals in if() scope gotcha!
by merlyn (Sage) on Mar 31, 2004 at 12:27 UTC
    There's a for-loop, with three expressions (sometimes called "C-style for").

    There's a foreach-loop, with single scalar (sometimes implied with $_) and a list of values to be walked (sometimes called a "csh-style foreach").

    They're definitely two different kinds of loops. However the text for and foreach may be used to introduce either one. The actual loop-style is determined by what follows.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Re: Re: Lexicals in if() scope gotcha!
by Ovid (Cardinal) on Mar 31, 2004 at 06:48 UTC

    They are aliases. If you look, you see that for and foreach have been used differently. This should clarify that.

    #!/usr/local/bin/perl5.9.1 print "foreach1...\n"; foreach (Foo->new) {} print "after foreach\n"; + print "for...\n"; for (my $object = Foo->new; 1 < 0; ) {} print "after for\n"; + print "foreach2...\n"; foreach (my $object = Foo->new; 1 < 0; ) {} print "after foreach\n"; + package Foo; sub new { my $self = bless {},shift; print "CREATED $self\n"; $self } sub DESTROY { print "DESTROYED $_[0]\n" } __END__ foreach1... CREATED Foo=HASH(0x81249dc) DESTROYED Foo=HASH(0x81249dc) after foreach for... CREATED Foo=HASH(0x8124ac0) after for foreach2... CREATED Foo=HASH(0x81249dc) after foreach DESTROYED Foo=HASH(0x81249dc) DESTROYED Foo=HASH(0x8124ac0)

    Cheers,
    Ovid

    New address of my CGI Course.