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

前端之家收集整理的这篇文章主要介绍了如何从Perl中的模块导出名为’import’的函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写了一个特殊的导入函数,将在几个地方使用,我希望能够“使用ImportRenamer;”在这些模块中,让他们使用从ImportRenamer获得的导入.我该怎么办?

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

解决方法

UPDATE

现在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”之外,您不需要做任何特殊操作.使用已经调用import(),参见perldoc use

use Module LIST

Imports some semantics into the current package from the named module,
generally by aliasing certain subroutine or variable names into your package.

It is exactly equivalent to:

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

猜你在找的Perl相关文章