Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: 'our' is not 'my'

by ikegami (Pope)
on Oct 26, 2007 at 12:02 UTC ( #647367=note: print w/ replies, xml ) Need Help??


in reply to 'our' is not 'my'

There is a catch with our that doesn't exist with use vars:

package AA; $AA::var = __PACKAGE__; our $var; print "$var\n"; package BB; $BB::var = __PACKAGE__; print "$var\n"; # Prints 'AA'.

Using curlies when using multiple packages in one file avoids the problem.

{ package AA; $AA::var = __PACKAGE__; our $var; print "$var\n"; } { package BB; $BB::var = __PACKAGE__; print "$var\n"; # Compile error! }

Keeping that exception in mind, our is like no strict 'vars'; on a per-var basis.


Comment on Re: 'our' is not 'my'
Select or Download Code
Re^2: 'our' is not 'my'
by ruzam (Curate) on Oct 26, 2007 at 15:45 UTC
    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?

      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?

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://647367]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (9)
As of 2014-08-29 00:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (275 votes), past polls