[oak perl] my operator question
Zed Lopez
zed.lopez at gmail.com
Tue Mar 8 09:52:29 PST 2005
On Tue, 08 Mar 2005 07:38:47 -0500, Sandy Santra <santranyc at yahoo.com> wrote:
> why does this work:
> but not this:
>
> use strict;
> my @numbers = qw(1 4 6);
> my $total = 0;
> $total += $_ for @numbers;
> print $total;
>
> [Global symbol "$total" requires explicit package name at test line 3.
> Global symbol "$total" requires explicit package name at test line 4.]
It works for me on Perl 5.8.5 on Fedora Core 3.
> and adding "my" this way doesn't work either:
>
> use strict;
> my @numbers = qw(1 4 6);
> my $total += $_ for @numbers;
> print $total;
You shouldn't do end-of-line modifiers (if, unless, while, for) with
my statement. You're using a new, undef'd $total each time through the
for loop. And it's undef after the loop, too. It seems to be the
equivalent of:
my @numbers = qw(1 4 6);
my $total;
for (@numbers) {
my $total;
$total += $_;
}
print $total;
That is, while you do succeed in declaring a lexically scoped varable
named $total in the main program, it's as if there were a different
lexically scoped variable named $total for the purposes of the for
loop.
Zed
More information about the Oakland
mailing list