tags:

views:

82

answers:

1

The below program prints "var = 13" and "var = 13". Shouldn't it print "var = 3" and "var = 13"?

use warnings;
use strict;

package p1;
our $var = 3;

package p2;
our $var = 13;
sub temp
{
    package p2;
    print "var = $var\n";
}

package p1;
print "var = $var\n"; #This prints var = 13. Why is it picking p2::var as the current package is p1?

&p2::temp;
+12  A: 

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";
Chas. Owens
Limiting the scope of package statements is also a very good idea.
daotoad
@daotoad: Agreed! I always try to use enclosing `{}` whenever using more than one `package` declaration in a single file (which I also try to avoid as much as possible).
Ether