in reply to Our Across Multiple Files?
our, like my, is a lexically-scoped declaration. That means it holds sway over a particular region of the source code -- from the declaration down to the end of the block that the declaration is in.
The effect of an our declaration is a bit subtle. It allows you to use a global variable (i.e. a package variable) without having to qualify it with the name of the package. So far so good, but the complication arises when you change the current package within the scope of the our declaration.
use strict; package foo; our $x; # Declare $x as an abbreviation for $foo::x $x = 23; package bar; print $x; # Still refers to $foo::x even # though we're now in package 'bar'
When you understand that, you'll see how to use our across multiple files. The important thing is to make sure that the declaration is in the same package each time. For example:
# This is test.pl use strict; our $foo = "Hello!\n"; use Bar; Bar->test();
# This is Bar.pm use strict; our $foo; package Bar; sub test { print $foo; } 1;
A more difficult question is why you'd want to do this. Using a global variable from within a package violates encapsulation. If you find yourself needing to do it, that's probably a sign that your code needs to be redesigned.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Our Across Multiple Files?
by Anonymous Monk on Dec 17, 2001 at 22:46 UTC | |
by djantzen (Priest) on Dec 18, 2001 at 08:18 UTC | |
by mr_mischief (Monsignor) on Dec 18, 2001 at 00:57 UTC |