Introduction to mod_perl (part 4): Perl Basics - Using the Perl Aliasing Feature to Share Global Variables (
Page 5 of 9 )
As the title says you can import a variable into a script or module
without using Exporter.pm. I have found it useful to keep all the
configuration variables in one module My::Config. But then I have
to export all the variables in order to use them in other modules,
which is bad for two reasons: polluting other packages' name spaces
with extra tags which increases the memory requirements; and adding
the overhead of keeping track of what variables should be exported
from the configuration module and what imported, for some particular
package. I solve this problem by keeping all the variables in one
hash %c and exporting that. Here is an example of My::Config:
package My::Config;
use strict;
use vars qw(%c);
%c = (
# All the configs go here
scalar_var => 5,
array_var => [qw(foo bar)],
hash_var => {
foo => 'Foo',
bar => 'BARRR',
},
);
1;
Now in packages that want to use the configuration variables I have
either to use the fully qualified names like $My::Config::test,
which I dislike or import them as described in the previous section.
But hey, since I have only one variable to handle, I can make things
even simpler and save the loading of the Exporter.pm package. I
will use the Perl aliasing feature for exporting and saving the
keystrokes:
package My::HTML;
use strict;
use lib qw(.);
# Global Configuration now aliased to global %c
use My::Config (); # My/Config.pm in the same dir as script.pl
use vars qw(%c);
*c = \%My::Config::c;
# Now you can access the variables from the My::Config
print $c{scalar_var};
print $c{array_var}[0];
print $c{hash_var}{foo};
Of course $c is global everywhere you use it as described above, and
if you change it somewhere it will affect any other packages you have
aliased $My::Config::c to.
Note that aliases work either with global or local() vars - you
cannot write:
my *c = \%My::Config::c; # ERROR!
Which is an error. But you can write:
local *c = \%My::Config::c;
For more information about aliasing, refer to the Camel book, second
edition, pages 51-52.