2011-09-02 20 views
2

我有一个模块,它看起来像这样:的Perl如何当模块在运行中输入访问FUNC

package Test; 
use strict; 
use warnings; 

sub hello { 
    my $val = shift 
    print "val = $val\n"; 
} 

,并在其他模块中我插入这个是这样的:

my $module = 'Test' 
eval "require $module"; 

如何在第二个模块中调用函数hello /我的意思是像一个函数不像方法/。

回答

3

您可以使用符号引用:

{ 
    no strict 'refs'; # disable strictures for the enclosing block 
    &{ $module . '::hello' }; 
} 

或者,您可以将该功能导出到呼叫包(请参阅Exporter):

package Test; 
use Exporter 'import'; 
our @EXPORT = qw(hello); 

sub hello { 
... 
} 

然后在你的代码:

my $module = 'Test' 
eval "use $module"; 
hello("test"); 
+2

在最后一种情况下,'eval'必须改为a)'use'而不是'require'或b)'import'必须手动调用。至少我认为是这样的... – musiKk

+0

@musiKk:谢谢,纠正。 –

+0

一个10倍我也是:) – bliof

1

您可以使用相同的EVAL这个目的:

my $module = 'Test' 
eval "require $module"; 

eval $module . "::hello()"; 

您也可以访问符号表,并得到参考所需子代码:

my $code = do { no strict 'refs'; \&{ $module . '::hello' } }; 
$code->(); 

但这并不这么看清洁。

但是,如果你需要的包名称的方法,如呼叫,你可以使用:

$module->new(); 

这也可能是有用的

+0

我会好好第二片断就可以在此使用'EVAL EXPR'的任何一天。 – ikegami

2

另一种方式:

$module->can('hello')->('test');