From the first paragraph of perldoc -f our
:
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.
Your first our
creates an alias of $p1::var
named $var
in the current scope. That scope runs until the end of the file (package
statements do not create a new scope). But then you create a new alias to $var
($p2::var
). So that alias lasts until the end of the scope (i.e. the file) or the next redefinition of the alias.
If you want to limit the scope of our
, create a new scope:
#!/use/bin/perl
package p1;
use strict;
use warnings;
our $var = 3;
{
package p2;
use strict;
use warnings;
our $var = 13;
}
print "$var in package ", __PACKAGE__, "\n";
{
package p2;
use strict;
use warnings;
our $var;
print "$var in package ", __PACKAGE__, "\n";
}
print "$var in package ", __PACKAGE__, "\n";