[ABE.pm] 'for' statement Q
Walt Mankowski
waltman at pobox.com
Fri Aug 15 11:17:43 PDT 2008
On Fri, Aug 15, 2008 at 01:56:16PM -0400, Faber J. Fedor wrote:
> 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'
>
This sets $_ locally to each element of the array within the loop, but
restores the old value afterwards. I seem to recall that's a newish
behavior, and older versions of Perl would have trashed $_.
>
> foreach (@array, my $i = 0; $i<3; $i++) {
> print; # prints foobar three times?!
> }
That last one is a C-style for loop which doesn't muck with $_.
> Who knew you could have so much fun with a simple 'for' statement! :-)
I think maybe you need to do some last-minute cramming with the camel
book, or at least the llama. This is all pretty basic stuff.
Walt
More information about the ABE-pm
mailing list