Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include all/some of the "sub modules" in a Perl script?

I'll just start out by saying I am not at all experienced with creating Perl modules so I'm sorry if I'm way off here.

Let's say I am creating a few modules:

foo::bar
foo::bar::a
foo::bar::b

Since I don't know what they are called, I am calling the a.pm and b.pm modules "sub modules" since they are related to the bar.pm module, but could still be somewhat independent.

So one of my Perl scripts could use foo::bar::a, another script could use foo::bar::b, and maybe I have another script that needs to use functions from both "a" and "b". Instead of saying this:

use foo::bar;
use foo::bar::a qw(one two);
use foo::bar::b;

I want to do something like this:

use foo::bar qw(:a :b);

In my mind, that would give my script access to everything in bar.pm, a.pm, and b.pm.

I tested something like this, and I was obviously wrong.

Is something like this possible? I suppose I could have bar.pm use a.pm and b.pm, and then have "wrapper" functions that pass the call onto the "sub modules" but it seems like there would be an easier way.

like image 558
BrianH Avatar asked Mar 02 '23 00:03

BrianH


2 Answers

Look at my Test::Data module for an example about doing that. Even though you can make it happen, I've never been terribly fond of the result. You might want to consider a Plugin or Mixin approach instead. There are some modules on CPAN that can help with this.

Here's the custom import that I wrote for Test::Data:

sub import 
    {
    my $self   = shift;
    my $caller = caller;

    foreach my $package ( @_ )
        {
        my $full_package = "Test::Data::$package";
        eval "require $full_package; 1";
        if( $@ )
            {
            carp "Could not require Test::Data::$package: $@";
            }

        $full_package->export($caller);
        }

    }
like image 152
brian d foy Avatar answered Mar 03 '23 22:03

brian d foy


Yes, you can do that. It will probably involve writing a custom 'sub import' in foo::bar that interprets incoming arguments the way you want.

Probably you're using Exporter right now, and it's its lack of support for your syntax that's the issue. You'll find that there's nothing particularly special about the module syntax Exporter implements; it's just a common convention. You'll likely want to look at how it does business to get insight into how you'll want to, though.

like image 28
chaos Avatar answered Mar 03 '23 22:03

chaos