Search code examples
perlperl-module

Setting Perl module parameters and using Exporter at the same time


When using Perl modules, there is sometimes a little bit of configuration required. In such cases, I am implementing a custom import function in my module. (Pragmas are omitted for brevity).

Api.pm

package Api;

# Default settings
my %PARAMS = (
     name => 'google',
     url => 'www.google.com'
);

sub import {
    my ( $pkg , %args )= @_;
    while ( my ($k,$v) = each %args ) {
        $PARAMS{$k} = $v;
}

sub some_method {
   # ...
}

sub another_method {
   # ...
}

Doing that, I can easily configure it when using it in a script.

script.pl

use Api ( name => 'stackoverflow', url => 'http://stackoverflow.com' );

But now I also want to export the module function some_method. Normally you do this using the Exporter module. But inheriting from this module overwrites my implementation of import.

From the client point of view, I had something in mind like

 use Api ( name => 'stackoverflow', 
           url => 'http://stackoverflow.com' ,
           import => [ 'some_method' ,'another_method' , ... ] );

But here I am stuck.

How can I use Exporter in my module Api.pm to export the functions?

Can I use it at all?


Solution

  • In the example, I used a hash reference as the first argument to use Api:

    package Api;
    
    use warnings;
    use strict;
    
    use Exporter;
    our @EXPORT_OK = qw{ test };
    
    my $params;
    
    sub import {
        $params = splice @_, 1, 1;
        goto &Exporter::import
    }
    
    sub test {
        print $params->{test}, "\n";
    }
    
    1;
    

    Testing code:

    use Api { test => scalar localtime }, qw{ test };
    test();