http://www.perlmonks.org?node_id=647411


in reply to Re: 'our' is not 'my'
in thread 'our' is not 'my'

In your first example, how is it that 'our $var;' in package AA makes $var available to both package BB and package main? Why does package BB fall back to AA's result without any kind of warning?

Replies are listed 'Best First'.
Re^3: 'our' is not 'my'
by ikegami (Patriarch) on Oct 26, 2007 at 16:09 UTC

    I prefer to think of our as the equivalent of no strict 'vars' for a single variable, but in reality, our creates a lexically-scoped variable aliased to a package variable.

    In effect,
    our $var;
    is the same as
    use Data::Alias;
    alias my $var = $__PACKAGE__::var;
    (Syntax issues aside.)

    Unlike blocks and files, packages aren't lexical scopes. Switching package neither destroys the our variable (because the our variable is lexically scoped) nor change to which package variable the our variable is aliased (because package doesn't know anything about the our variable).

      I guess that also explains why I can put 'our $var;' in package BB and have this version of $var carried through main. Each use of 'our' replaces any previous alias for the remainder of the execution. I'll have to re-train my brain on what to expect from packages :)

      Makes me a little nervous that Perl would allow this without some kind of warning. Also makes me wonder what kind of problems could be made easier using 'our' in this way?
        The point is that Perl is willing to trust you. Your telling it our $var means “I and all my friends in this lexical scope want to use this variable without qualification” (that's why it's the first person plural!). Since it believes that you know what you're doing, it doesn't want to warn you later when you do just what you said that you were going to do.