ServersThe Perl Basics You Need To Know Page 2

The Perl Basics You Need To Know Page 2

ServerWatch content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

So the is shared between the My::HTML package
and It will work vice versa as well, if you create the
object in My::HTML but use it in You have
true sharing, since if you change in, 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 to

 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 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/ is in the same dir as
  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 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

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

Get the Free Newsletter!

Subscribe to Daily Tech Insider for top news, trends & analysis

Latest Posts

Related Stories