in reply to the "our" declaration ?!!
"our" has exactly the same scope like "my", it's the exact analogon but for package variables.
If the compiler encounters a simple* variable name like $var it has to decide where to store and look up it's value. This is decided by the last "declaration"¹ (my or our) within the same "lexical scope", which doesn't necessarily mean the variable itself is "lexical" (that means: private to the lexical scope).
So "our" gives you a much more orthogonal behavior to "my" than simply relying on "simple variables are by default packagevars except when declared with my"².use warnings; use strict; $\="\n"; $,="\t"; our $x="main"; { package one; our $x="one"; package two; our $y="two"; { my $x="private"; print $x,$y; # private $x , $two::y } # end of second scope print $x,$y; # $one::x , $two::y } # end of first scope print $x; # $main::x print $one::x; # variable still exists in that namespace # without being bound to $x # but the private $x of the second scope # is definitely lost! # end of file scope __END__ private two one two main one
Cheers Rolf
UPDATES: extended code example
(*) "simple" means without explicit package name e.g. $package::var
(¹) I'm not sure if "declaration" is the best term, maybe better "binding" or "aliasing", the perldoc talks about "associating"
(²) without "strict" or "vars"
well the explanation in "perldoc -f our" is quite good!
"our" associates a simple name with a package variable in the current package for use within the current scope. When "use strict ’vars’" is in effect, "our" lets you use declared global variables without qualifying them with package names, within the lexical scope of the "our" declaration. In this way "our" differs from "use vars", which is package scoped.Unlike "my", which both allocates storage for a variable and associates a sim‐ ple name with that storage for use within the current scope, "our" associates a simple name with a package variable in the current package, for use within the current scope. In other words, "our" has the same scoping rules as "my", but does not necessarily create a variable.
...
|
|---|