So the is shared between the
My::HTML
package
and script.pl
. It will work vice versa as well, if you create the
object in My::HTML
but use it in script.pl
. You have
true sharing, since if you change in
script.pl
, it
will be changed in My::HTML
as well.
What if you need to share between more than two packages?
For example you want My::Doc to share as well.
You leave My::HTML
untouched, and modify script.pl to
include:
use My::Doc qw();Then you add the same
Exporter
code that I used in
My::HTML
, intoMy::Doc
, so that it also exports
.
One possible pitfall is when you want to use
My::Doc
in both
My::HTML
and script.pl. Only if you adduse My::Doc qw();into
My::HTML
willbe shared. Otherwise
My::Doc
will not shareany more. To make things
clear here is the code:script.pl: ---------------- use vars qw(); use CGI; use lib qw(.); use My::HTML qw(); # My/HTML.pm is in the same dir as script.pl use My::Doc qw(); # Ditto = new CGI; My::HTML::printmyheader();My/HTML.pm ---------------- package My::HTML; use strict; BEGIN { use Exporter (); @My::HTML::ISA = qw(Exporter); @My::HTML::EXPORT = qw(); @My::HTML::EXPORT_OK = qw(); } use vars qw(); use My::Doc qw(); sub printmyheader{ # Whatever you want to do with ... e.g. print ->header(); My::Doc::printtitle('Guide'); } 1;My/Doc.pm ---------------- package My::Doc; use strict; BEGIN { use Exporter (); @My::Doc::ISA = qw(Exporter); @My::Doc::EXPORT = qw(); @My::Doc::EXPORT_OK = qw(); } use vars qw(); sub printtitle{ my = shift || 'None'; print ->h1(); } 1;Using the Perl Aliasing Feature
to Share Global VariablesAs the title says you can import a variable into a script or module without
usingExporter.pm
. I have found it useful to keep all the
configuration variables in one moduleMy::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;