home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book Home Programming PerlSearch this book

32.15. Exporter

Inside your MyModule.pm file:

package MyModule;

use strict;
use Exporter;

our $VERSION = 1.00;           # Or higher...
our @ISA = qw(Exporter);

our @EXPORT      = qw(f1 %h);  # Symbols imported by default.
our @EXPORT_OK   = qw(f2 f3);  # Symbols imported only by request.
our %EXPORT_TAGS = (           # Mappings for :shortcuts.
    a => [qw(f1 f2 f3)],
    b => [qw(f2 %h)],
);

# Your code here.

1;
From a program or another module that makes use of your module:
use MyModule;                  # Import everything in @EXPORT.
use MyModule ();               # Load module, no imports at all.
use MyModule "f1", "f2", "%h"; # Two subs and a variable.
use MyModule qw(:DEFAULT f3);  # All in @EXPORT + one sub.
use MyModule "f4";             # Fatal because f4 not exported.
Whenever anyone invokes a use declaration to load your module, it calls the import method from your module to fetch any symbols it needs into the package of the invoker. Your module (the one doing the exporting) can define the import method any way it pleases, but the standard way is to inherit the method from the Exporter class module. That is what the code above arranges.

The Exporter module serves as a base class for modules that wish to establish their own exports. Oddly, object-oriented modules typically don't use Exporter, since they don't normally export anything (method calls don't need to be exported). However, the Exporter module itself is accessed in an OO fashion because of the @ISA array you installed, as in our example. When another program or module uses your module, the import method is invoked as a class method in your module: MyModule->import(LIST). However, since you didn't define an import method in your module, you'll automatically make use of the Exporter::import method through inheritance.

The module's @EXPORT array contains a list of symbols (functions and even variables) that the calling code automatically imports with an unadorned use statement. The @EXPORT_OK array holds symbols that can be imported if specifically requested by name. The $VERSION number is consulted if the use statement requests that a particular version (or newer) of the module. Many, many other features are available. See Chapter 11, "Modules", as well as the online manpage for the Exporter module.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.











??????????????@Mail.ru