[Wellington-pm] A question about scopes

Grant McLean grant at mclean.net.nz
Mon Mar 20 14:02:20 PST 2006


On Tue, 2006-03-21 at 09:22 +1200, Cliff Pratt wrote:
> Say I have a Package and a PERL script. If the package uses a variable 
> $foo, and so does the script, I should be able to access the script's 
> version of $foo by $main::foo in the package. Am I correct?

Yes (assuming the script didn't declare a package name) but that would
be a bit dodgy.  If your package needs some data from your script then
your script should pass it in as an argument to a subroutine.

> If $bar is defined in a sub in the package (eg my $bar), its scope is 
> just the sub, isn't it? 

Yes, it can only be accessed from that sub or anything that has been
passed a reference to it (eg: if the sub returned a reference).

> How do I make the scope "global" to the package 
> so that any sub can find it? (I know "global" is not technically correct 
> here) Define it outside any subs in the package?

Yes, a 'my' variable declared (by convention) at the start of a package
will be visible to all code in the file (including other packages
defined in the same file).

A 'my' variable will not be visible from outside it's scope.  Fully
qualified names like $Package::var are for global variables, not
lexically scoped 'my' variables.

>  Does code outside a sub in a package ever get executed?

Yes. When the package is first 'use'd or 'require'd, all code in the
file will be compiled and then the bare lines (typically variable
initialisation) will be executed.

> If I make $bar "global" to the package, is there a clever way of 
> avoiding qualifying it all the time to distinguish it from the script's 
> version of $bar?

I'm not sure what you're asking here.

Perl has all sorts of clever tricks for aliasing variables (or subs) and
importing them from one package into another.  But you should almost
never do that.

Perhaps if we saw some of your real code, we might understand your
intent more clearly.

Regards
Grant



More information about the Wellington-pm mailing list