[oak perl] my operator question

Steve Fink sfink at reactrix.com
Tue Mar 8 11:07:41 PST 2005


Zed Lopez wrote:
> On Tue, 8 Mar 2005 09:52:29 -0800, Zed Lopez <zed.lopez at gmail.com> wrote:
> 
>>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;
> 
> 
> Oops. I contradicted myself there -- if it's equivalent to the latter,
> it's not the case that you're using a new, undef'd $total each time
> through the for loop. I really don't know what Perl might be doing
> inside that for loop; I only know the external behavior.

Why not? It seems like your description was correct. The inner $total is 
lexically scoped to the for block, so it starts out undef, gets assigned 
to undef plus each of the numbers (equiv to the number), then goes out 
of scope and is forgotten before the next iteration. It's confusing that 
it's the same $total during each iteration, but the value gets reset. 
Still, that's what I would expect from:

   for (1..3) {
     print "Iteration $_\n";
     if (42 > 0) {
       my $x;
       $x += $_;
       print "Yow!\n" if $x > 3;
     }
   }

I wouldn't expect that to print "Yow!", since $x really shouldn't 
survive outside of that if statement.

The exact translation of the original would actually be

   for (@numbers) {
     my $total += $_;
   }

as can be seen with

   perl -MO=Deparse -e 'my $total += $_ for (1..3)'

but I think it's the same.

The confusing bit is that the variable really is the same:

   perl -le 'for (1..3) { my $x; print \$x; }'

Hmm... so what does this do?

   perl -le 'for (1..3) { if (1) { my $x; my $y = \$x; $$y += $_; print 
"$y=$$y" } }'

I guess that means that the value really is reset at runtime when the 
'my' is encountered? Yes, it sounds like it, from reading through 
perlsub, when it talks about 'my' having both compile-time and runtime 
effects.


More information about the Oakland mailing list