Section 15.2. Importing with Exporter


15.2. Importing with Exporter

In Chapter 3, 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, we can look at the symbol table (where all subroutines and many variables are named), see what is defined, and alter those definitions. You saw a bit of that back in the AUTOLOAD mechanism earlier in Chapter 14. In fact, as the author of File::Basename, if we simply want to force filename, basename, and fileparse from the current package into the main package, we can write import like this:

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

Boy, is that cryptic! And limited. What if the caller didn't want fileparse? What if the caller 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 we do is add:

 use base 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[*] and export them to the caller's package.

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




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net