in reply to "our" versus "my" for class data

I'm not sure whether you meant to imply this or not, but one big difference between using my and our, is that our does not really create a closure.* You hint at this when you say our "allow[s] it to be set from outside the package," but I just thought it could use some explicit clarification.

* Update: actually, the snippet using our does create a closure, but the thing being closed on is not the variable itself. See this post by tilly for details.

Compare:

{ our $foo; sub inc { ++$foo } } print inc for 1 .. 5; our $foo; print ++$foo;

To:

{ my $foo; sub inc { ++$foo } } print inc for 1 .. 5; my $foo; print ++$foo;

The neat thing about closures is that they allow the variable to persist, while also protecting it from the outside. Using our does not.

Replies are listed 'Best First'.
Re^2: "our" versus "my" for class data
by dragonchild (Archbishop) on Aug 08, 2004 at 02:47 UTC
    You're mostly correct, but not completely. Closures "protect my variables from the outside" because my variables are declared on the functions scratchpad. our variables are declared on what could be considered the package's scratchpad.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

      Perhaps I'm missing something, but I don't see what about my post was incorrect. Were you pointing out an error on my part, or just adding some more information?

        If he was adding information, it was somewhat misleading. However your post was also technically incorrect.

        A closure closes over the current lexical environment. That does not mean that the current lexical environment is private, whatever else shares it can change it. Frequently nothing else shares that environment, but not always. An extreme demonstrating being a function that returns several connected closures - each of which can change the private data that the others look at. (I've done this, but more often in JavaScript than in Perl. It can be a nice technique to use to coordinate between UI elements.)

        In the case of our, the current lexical environment includes the fact that certain variables are actually the equivalent package variable. In that case the current lexical environment includes some very non-private stuff. So yes, our creates a closure, but not one that acts a lot like what you'd normally think of as a closure.