设置Perl模块参数,同时使用Exporter

Setting Perl module parameters and using Exporter at the same time

使用 Perl 模块时,有时需要进行一些配置。 在这种情况下,我在我的模块中实现了一个自定义 import 函数。 (为简洁起见省略了 Pragma)。

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 {
   # ...
}

这样做,我可以在脚本中使用它时轻松配置它。

script.pl

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

但是现在我也想导出模块功能some_method。通常您使用 Exporter 模块来执行此操作。但是从这个模块继承会覆盖 my 实现 import.

从客户的角度来看,我有这样的想法

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

但是我卡在这里了。

如何在我的模块 Api.pm 中使用 Exporter 导出函数?

我可以使用它吗?

在示例中,我使用哈希引用作为 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;

测试代码:

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