2011-09-02 60 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');