in reply to Two Questions on "my"

I was going to answer question one by suggesting that it might be more useful to think of my as a compile-time scoping contruct rather than something that actually gets executed. So I wrote some sample code to illustrate my point. I guess it was a useful excercise, because now I'm confused! Here are the three scripts and their outputs:
use strict; foreach (0 .. 10) { my $foo; $foo = 0 unless $_; print $foo++, ' '; } 0 0 0 0 0 0 0 0 0 0 0 use strict; foreach (0 .. 10) { my $foo = 0 unless $_; print $foo++, ' '; } 0 0 1 2 3 4 5 6 7 8 9 use strict; foreach (0 .. 10) { my $foo = 0 unless $_; print $foo, ' '; $foo++ } 0 1 2 3 4 5 6 7 8 9
Okay, I was wrong about the not-getting-executed stuff. But can anyone explain what's going on with the second and third examples? It's almost as if the scope of the my were restricted to the statement it's used in and that the $foo getting printed and incremented is a different variable -- at least after the first time through the loop (if that even makes sense). But if that were the case, why didn't strict complain?

Replies are listed 'Best First'.
Re: Re: Two Questions on "my"
by Somni (Friar) on May 24, 2004 at 05:44 UTC

    I'm not sure if I've got some sort of mental filter that spots these, or if it's a commonly encountered problem, but this is the third time in a week someone has asked this question.

    The answer is that my has both a compile- and a run-time effect. The compile-time effect allocates space for the variable and lets it pass strict. The run-time effect initializes the variable. If you conditionalize the initialization you have, in effect, a static variable; one that retains its value beyond scope exit.

    I've explained it in more detail, with a documentation reference, here, and it has been covered in a thread here.

      Yup. This is the kind of stuff that makes my Python buddies wince when they regard my affinity for Perl. But their desks are tidy. Mine is messy. There's obviously a connection.

      Thanks, Somni!