[LON-CAPA-dev] A lesson in globals

Guy Albertelli II lon-capa-dev@mail.lon-capa.org
Fri, 21 Mar 2003 17:37:33 -0500 (EST)


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-