[oak perl] operator question--still confused
Zed Lopez
zed.lopez at gmail.com
Tue Mar 8 14:10:58 PST 2005
You might like to take another pass through Coping With Scoping.
http://perl.plover.com/FAQs/Namespaces.html
> My problem doesn't involve a loop, merely understanding how "use strict"
> and "my" are supposed to work together. I may have copied my examples
> incorrectly (sorry!), so they are set forth again here below. I started
> out with:
>
> my @numbers = qw(1 4 6);
> $total += $_ for @numbers;
> print $total;
Here, $total is a package variable (implicitly in the main:: package.)
Without using strict, Perl will let you make up new package variables
whenever you feel like it. (This is a feature for one-liners, but not
for anything longer than a few lines, which is why Perl people are so
avid about recommending using strict.)
> which worked, producing a value of "11" to my DOS window. Then I decided
> to add "use strict;" at the beginning:
>
> use strict;
> my @numbers = qw(1 4 6);
> $total += $_ for @numbers;
> print $total;
>
> That gave me errors, asking me to explicitly define $total (I assume with
> "my"). But when I run the following, I get nothing (no return of the value
> and no error messages):
That's a big part of the point of strict: now you can't just make up
package variables on the fly. You can predeclare them with 'use vars',
or you can use lexical variables (declared with 'my') instead.
> use strict;
> my @numbers = qw(1 4 6);
> my $total += $_ for @numbers;
> print $total;
>
> I can't figure out why my first example works, whereas my third doesn't. I
> figure this is just something simple I'm missing.
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;
More information about the Oakland
mailing list