The Perl Basics You Need To Know Page 2

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, into My::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 add

  use My::Doc qw();

into My::HTML will be shared. Otherwise My::Doc will not share any more. To make things clear here is the code:

  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;

  package My::HTML;
  use strict;
    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();

  package My::Doc;
  use strict;
    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();

Using the Perl Aliasing Feature to Share Global Variables

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',

This article was originally published on Aug 2, 2000

Thanks for your registration, follow us on our social networks to keep up-to-date