Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl: export symbols from module that has > 1 package

Tags:

perl

module foo/bar.pm

package foo::bar;
stuff
stuff
package foo::wizzy;
require Exporter;
our @ISA=qw(Exporter);
our @EXPORT=qw(x);
use constant
{
  x=>1
};

a consumer that does

use Foo::bar;

does not get the foo::wizzy::x export

I know I can make it two separate modules, but still I should be able to make this work, shouldn't I?

like image 471
pm100 Avatar asked Nov 09 '09 23:11

pm100


2 Answers

You can do it using Exporter's export_to_level method to have the "main package" re-export the "other" package's symbols like so:

sub import {
   my $self = shift;
   $self->export_to_level(1, @_);
   Some::Other::Module->export_to_level(1);
}

though if Some::Other::Module does something more complicated than "export everything" you will probably need fancier handling for @_.

I really have to ask why, though—I can't imagine a use for this that's compatible with the words "good code" :)

like image 114
hobbs Avatar answered Nov 10 '22 20:11

hobbs


When you call use foo::bar, what actually happens is essentially:

BEGIN {
    require foo::bar;
    foo::bar->import;
}

(see perldoc -f use)

So import is never getting called on foo::wizzy. If you want to import those symbols as well, you can call BEGIN { foo::wizzy->import } yourself (after use foo::bar). Or, as you said, just split these two packages into separate files, which would be much more human-readable.

(By the way, it's not advisable to use lower-cased package names, as those are generally reserved for perl pragmata.)

like image 44
Ether Avatar answered Nov 10 '22 21:11

Ether