in reply to package variable scope
Your last statement uses $VAR unqualified, so it is the last $VAR of whatsoever package that has been allocated - which happens to be the incarnation of $VAR in package C.
Consider:
use strict; use warnings; our $VAR=5.0; sub printit{print "Package Main VAR=$VAR\n";} package A; our $VAR=2.0; sub printit{print "Package A VAR=$VAR\n";} package B; our $VAR=3.0; sub printit{print "Package B VAR=$VAR\n";} package C; our $VAR=4.0; sub printit{print "Package C VAR=$VAR\n";} package main; $VAR="foo"; A::printit; B::printit; C::printit; printit; print "Package Main VAR=$VAR\n"; print <<EOH; A: $A::VAR B: $B::VAR C: $C::VAR main: $main::VAR whatever: $VAR EOH __END__ Package A VAR=2 Package B VAR=3 Package C VAR=foo Package Main VAR=5 Package Main VAR=foo A: 2 B: 3 C: foo main: 5 whatever: foo
Declaring a variable as our creates a lexically scoped variable spanning packages, which will create a symbol table slot in the current package in which the our declaration ocurred. This lexical variable will be bound to the symbol table of that package until re-declared (think bless) into another package. Altering the unqualified alias results in altering the value in the symbol table slot of that last package. That is why you get foo for $C::VAR above: $VAR - unqualified - is still bound to package C when it is last modified in package main.
If you remove the our declaration after package B, then $VAR will yield 3 for both package A and B.
|
|---|