[ABE.pm] 'for' statement Q

Faber J. Fedor faber at linuxnj.com
Fri Aug 15 10:19:09 PDT 2008


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.

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?    

-- 
 
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