如何从Perl中的模块导出名为'import'的函数?

时间:2010-07-26 19:20:23

标签: perl

我写了一个特殊的导入函数,将在几个地方使用,我希望能够“使用ImportRenamer;”在这些模块中,让他们使用从ImportRenamer获得的导入。我该怎么做?

编辑:换句话说:如何在不运行的情况下导入'import'?

4 个答案:

答案 0 :(得分:3)

<强>更新

现在OP澄清了他的需求,这确实应该以类似于Exported的方式完成,确切地说,通过全局赋值将子引用注入调用者的命名空间。例如:

###############################################

package ImportRenamer; 
use strict;
sub import_me {
   print "I am a cool importer\n";
}

sub import { 
  my ($callpkg)=caller(0);
  print "Setting ${callpkg}::import to ImportRenamer::import_me\n"; 
  no strict "refs";
  *{$callpkg."::import"} = \&ImportRenamer::import_me; # Work happens here!!!
  use strict "refs";
}
1;

###############################################

package My; 
use strict;
use ImportRenamer; 
1;

###############################################

package My2; 
use strict;
use ImportRenamer; 
1;

###############################################

测试:

> perl -e '{  package main; use My; use My2; 1;}'
Setting My::import to ImportRenamer::import_me
I am a cool importer
Setting My2::import to ImportRenamer::import_me
I am a cool importer

原始回答

除了调用导入方法“import”之外,您无需执行任何特殊操作。 use已拨打import(),请参阅perldoc use

use Module LIST 
  

将一些语义从命名模块导入当前包中,   通常通过将某些子例程或变量名称别名到您的包中。

     

完全等同于:

 BEGIN { require Module; Module->import( LIST ); }

答案 1 :(得分:3)

您需要在模块中编写一个自定义import方法,该方法将导出您希望在调用命名空间中调用import的函数。

这是一些未经测试的代码:

package ImportMe;

sub import { 

    # Get package name
    my $caller = caller;

    # Install my_import into the calling package as import
    {    no strict 'refs';
         *{"${caller}::import"} = \&my_import;
    }

    return 1;
}

# renamed as import when installing
sub my_import {

   # do stuff

}

现在,您可以将use ImportMe;放入所有模块中,并安装import方法。

答案 2 :(得分:3)

作为替代方案,您可以使用Sub::Exporter

避免在符号表中乱码
package Your::Module;

use Sub::Exporter (
    -setup => {
        exports => {
            import => sub { return \&_real_import }
        },
        # the "default" group auto-exports "import" without the caller 
        # specifically asking for it
        groups => { default => [qw(import)] },
    }
);

sub _real_import { ... }

编辑添加了自动导出的“默认”组

答案 3 :(得分:2)

这样的事情怎么样:

package Your::Module;

use strict;
use warnings;

sub import { 
    # gets called by use Your::Module
    my ( $pkg ) = caller;

    no strict 'refs';
    *{ $pkg . '::import' } = \&_real_import;
}

sub _real_import { 
    # import function to be exported to caller
    print "blah blah";
}

这会手动将_real_import子分配给调用包命名空间的import插槽。如果您在BEGIN块中执行此操作,则import子应准备就绪并等待 包获得use d。