[Chicago-talk] Global variable behavior

Andrew Rodland andrew at cleverdomain.org
Wed Mar 3 18:54:18 PST 2010


On Wednesday 03 March 2010 08:20:26 pm Mithun Bhattacharya wrote:
> Hi Everyone,
> 
> A piece of my code is behaving in a way I didn't expect and I was hoping
> someone could enlighten me as to why..
> 
> -------------------------------------
> $ cat a.pl
> push @INC, '.';
> 
> our $c = 15;
> 
> require newbie;
> -------------------------------------
> $ cat newbie.pm
> package newbie;
> 
> print "first attempt: " . $c . "\n";
> print "second attempt: " . $::c . "\n";
> 
> 1;
> -------------------------------------
> $ perl a.pl
> first attempt:
> second attempt: 15
> -------------------------------------
> 
> The way I see it the our in a.pl should make it global across all
> namespaces. The second attempt does seem to say that did take place. What
> I am not sure is why the $c variable has become local in scope even though
> I haven't re-declared or redefined it in any way inside newbie.pm.

Because it's not declared in any way in newbie.pm. What "our $foo" does is 
*lexically* create a binding between the name $foo and the variable $foo in 
the current package. It doesn't make package variables any "more global" than 
they already are, and (silly tricks involving multiple packages in a file 
excluded) it doesn't let you refer to a variable in a different package 
without naming that package. If you want $::c, write $::c. And use strict so 
that your first example throws a compile-time error instead of silently 
breaking. :)

Andrew


More information about the Chicago-talk mailing list