[ABE.pm] 'for' statement Q

Walt Mankowski waltman at pobox.com
Fri Aug 15 10:37:03 PDT 2008


On Fri, Aug 15, 2008 at 01:29:57PM -0400, Walt Mankowski wrote:
> On Fri, Aug 15, 2008 at 01:19:09PM -0400, Faber J. Fedor wrote:
> > Yes, a question about the 'for' statement.  Can you beleive I'm teaching
> > a Perl class on Monday? :-)
> > 
> > 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:
> 
>   The "foreach" keyword is actually a synonym for the "for" keyword,
>   so you can use "foreach" for readability or "for" for brevity.  (Or
>   because the Bourne shell is more familiar to you than csh, so
>   writing "for" comes more naturally.)
> 
> > Why does that work?  My theory is this: 
> > 
> > First note that the $c,$m,$y are not the traditional three elements of a
> > for() loop (initial expression, incrementor, test) because those are
> > separated by semi-colons.  Here the $c, $m, $y are the initial
> > expression.  
> > 
> > Now, if the initial expression is true, the block will be executed. That
> > explains why the block is executed the first time ($_ <- $c).  But why
> > is the block executed two more times? My guess is the initial expression
> > is seen in a list context and the code block as a reference, i.e. a
> > scalar, and the scalar is applied to each element in the list.
> > 
> > That would explain why  'print $_ for(0)' produces an output even though
> > the initial expression is false, n'est pas?    
> 
> I think it's just that it's treating whatever's in the parens as a
> list, and iterating over that list.

It's not clear you know this from what you said, but this is the same
idea as this:

  my @list = ($c, $m, $y);
  for (@list) {
    print "$_\n";
  }

If you're not familiar with that syntax, you've got a lot of catching
up to do before you teach this class... :)

Walt


More information about the ABE-pm mailing list