John M. Dlugosz has asked for the wisdom of the Perl Monks concerning the following question:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: What exactly does 'our' do?
by John M. Dlugosz (Monsignor) on May 21, 2001 at 23:44 UTC | |
What exactly does the 'our' declaration do? When it was first introduced, the documentation was not clear. Now, the documentation is better and existing modules offers examples of what it's good for. First, let's look at it as compared with 'my'. The docs give this example:
Now if you try the same thing with 'my' instead of 'our',
you get the exact same result. So, the explaination in the docs of how 'our' does the scope thing An our declaration declares a global variable that will be visible across its entire lexical scope, even across package boundaries. The package in which the variable is entered is determined at the point of the declaration, not at the point of use is in fact no different from what 'my' does. We're already used to that kind of thing, and this is nothing new. So don't worry about it. (Understanding different scopes is another question, though.) The difference—the real purpose—is that 'my' variables are not entered into the run-time symbol table. In the second example above, there is no such thing as $Foo::bar, so the $bar variable cannot be accessed outside of its lexical scope or pointed to with a symboloc link. Since $bar is not an abbreviation for $Foo::bar, the fact that it crosses package boundaries is largely unnoticed. In the first example, our $bar is another name for $Foo::bar, and it is in the symbol table. However, the fact that it can be refered to as plain $bar works in exactly the same way as the 'my'. It's a lexical scope where the name $bar can be used, and where it is so used, it refers to the same memory as $Foo::bar. So, the difference between 'my' and 'our' is that 'my' variables are not in the symbol table, while 'our' variables are put in the current symbol table where the 'our' is encountered. In modules, a common use for 'our' is to declare global variables. The way they cross package boundaries is usually not noticed, with one package per class. With strict in effect, package variables would need to be refered to with full names, and an older way around that is with use vars. Anything that must be in the symbol table, such as the $EXPORTS and @ISA and any variables you want to be visible from outside of the module, cannot be 'my'. Previously you would either qualify all uses to them, or use a use vars line. Now, you can declare them with 'our' instead. | [reply] [d/l] [select] |