[ABE.pm] 'for' statement Q

Faber J. Fedor faber at linuxnj.com
Fri Aug 15 10:56:16 PDT 2008


On 15/08/08 13:29 -0400, Walt Mankowski wrote:
> On Fri, Aug 15, 2008 at 01:19:09PM -0400, Faber J. Fedor wrote:
> > I thought this was a typo
> > 
> >     for($c, $m, $y) { $_-= $k; }
> > 
> > where 'for' was written when the author (Dominus) meant to type 'foreach'.
> > But it turns out to work just like a foreach, IOW, it iterates over the
> > list and $_ is assigned $c then $m then $y.
> 
> That's because "foreach" and "for" are equivalent.  From perlsyn:

Interesting.  That means I can have an incrementor and a test condition
in my foreachs! I'm going to have to play with that...

<time passes>

This is interesting.  I _can_ have a test condition and incrementor in a
foreach, but it changes the behavior wrt to $_.  Check this out:

    #!/usr/bin/perl
    
    # example showing block scoping of variables
    
    $_ = "foobar";
    
    my @array = (1,2,3,4,5);
    
    foreach (@array) {
        print;           # prints 1,2,3,4, and 5
    }
    
    print;               # prints 'foobar'
    
    
    foreach (@array, my $i = 0; $i<3; $i++) {
        print;           # prints foobar three times?!
    }


Who knew you could have so much fun with a simple 'for' statement! :-)

-- 
 
Regards,
 
Faber Fedor
President
Linux New Jersey, Inc.
908-320-0357
800-706-0701

http://www.linuxnj.com





More information about the ABE-pm mailing list