[oak perl] operator question--still confused

Mark Bole mark at bincomputing.com
Thu Mar 10 08:23:27 PST 2005


Zed Lopez wrote:

>You might like to take another pass through Coping With Scoping.
>
>http://perl.plover.com/FAQs/Namespaces.html
>[...]
>
>The reason this fails _is_ about the for loop, as Steve and I
>discussed. $total is undef again after the for loop; you shouldn't use
>end-of-line modifiers like 'for' after 'my' statements.
>
>This works:
>
>use strict;
>my @numbers = qw(1 4 6);
>my $total = 0;
>$total += $_ for @numbers;
>print $total;
>
>
>  
>
This is why, as a matter of style, I don't like using "for" as an 
end-of-line modifier.  As the camel book says under the section 
"Maintainer Efficiency",

* Use foreach to mean foreach
* Parenthesize for clarity

I would write the code as follows to help make the block scope explicit:

use strict;
my @numbers = qw(1 4 6);
my $total;
foreach (@numbers) {
    $total += $_;
}
print $total;

-- 
Mark Bole
http://www.bincomputing.com
925-287-0366





More information about the Oakland mailing list