[LON-CAPA-dev] A lesson in globals

Gerd Kortemeyer lon-capa-dev@mail.lon-capa.org
Fri, 21 Mar 2003 18:02:58 -0500


That's all true, but what if you want the following:

* variable (like a tied hash) should NOT be available from outside the
package
* inside the package, you want to refer to it just by its name

Looks like "my $silly" as a package global works great for that.

Guy Albertelli II wrote:

> I noticed some things that I wanted to blather on about
>
> The sumamry is
>
> 'Don't declare a global variable using "my", things will act wacky'
>
> if you declare a global using my it becomes global to the file meaning
> it can be talked about with out namespace throuhgt a file. (And I
> don't know of a way to access it from another file)
>
> ie:
> ----- start test.pl -----
> package globaltest;
> use strict;
> my $silly='a';
> print '1'.$silly."\n";
> print '2'.$globaltest::silly."\n";
>
> package notglobaltest;
> print '3'.$silly."\n";
> print '4'.$globaltest::silly."\n";
> ----- end test.pl -----
>
> Note that $globaltest::silly never works and $silly always works
>
> If you want to declare a variable that is global to a package and want
> to be able to refer to it without using the full package reference you
> need to do 'use vars'
>
> ----- start test.pl -----
> package globaltest;
> use strict;
> use vars qw($silly);
> $silly='a';
> print '1'.$silly."\n";
> print '2'.$globaltest::silly."\n";
>
> package notglobaltest;
> # the line below will fail to compile
> # print '3'.$silly."\n";
> print '4'.$globaltest::silly."\n";
> ----- end test.pl -----
>
> Now the global is properly enclosed inside of the globaltest package
> and when inside notglobaltest I need to specify the package reference
> to get access to it.
>
> If you want to set a global and plan to always refer to it by it's
> fullname, you don't need to anything special:
> ----- start test.pl -----
> package globaltest;
> use strict;
> $globaltest::silly='a';
> #the line below will fail to compile
> #print '1'.$silly."\n";
> print '2'.$globaltest::silly."\n";
>
> package notglobaltest;
> # the line below will fail to compile
> # print '3'.$silly."\n";
> print '4'.$globaltest::silly."\n";
> ----- end test.pl -----
>
> Now only the full variable references work.
>
> --
> guy@albertelli.com  LON-CAPA Developer  0-7-7-1-
> _______________________________________________
> LON-CAPA-dev mailing list
> LON-CAPA-dev@mail.lon-capa.org
> http://mail.lon-capa.org/mailman/listinfo/lon-capa-dev