Learning Perl Objects, References & ModulesLearning Perl Objects, References & ModulesSearch this book

12.8. Importing with Exporter

Earlier we skipped over that "and now magic happens" part where the import routine (defined by the module author) is supposed to take File::Basename::fileparse and somehow alias it into the caller's package so it's callable as fileparse.

Perl provides a lot of introspection capabilities. Specifically, you can look at the symbol table (where all subroutines and most variables are named), see what is defined, and alter those definitions. You saw a bit of that back in the AUTOLOAD mechanism earlier. In fact, as the author of File::Basename, if you simply want to force filename, basename, and fileparse from the current package into the main package, you can write import like this:

sub import {
  no strict 'refs';
  for (qw(filename basename fileparse)) {
    *{"main::$_"} = \&$_;
  }
}

Boy, is that cryptic! And limited. What if you didn't want fileparse? What if you invoked use in a package other than main?

Thankfully, there's a standard import that's available in the Exporter module. As the module author, all you do is add:

use Exporter;
our @ISA = qw(Exporter);

Now the import call to the package will inherit upward to the Exporter class, providing an import routine that knows how to take a list of subroutines[71] and export them to the caller's package.

[71]And variables, although far less common, and arguably the wrong thing to do.



Library Navigation Links

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