我正在试图弄清楚如何为Perl模块进行函数引用.我知道如何在模块外部进行,但在一个模块内部?考虑这样的代码:
==mymodule.pm==
1 sub foo { my $self = shift; ... }
2 sub bar { my $self = shift; ... }
3 sub zip {
4 my $self = shift;
5 my $ref = \&foo;
6 $self->&$foo(); # what syntax is appropriate?
7 }
==eof===
Run Code Online (Sandbox Code Playgroud)
看看上面的第5-6行.(1)首先定义函数引用,以及(2)解引用它的正确语法是什么?
mob*_*mob 23
TMTOWTDI
定义函数引用:
$ref = \&subroutine;
$ref = sub { BLOCK };
$ref = "subroutineName"; # or $ref = $scalarSubroutineName
Run Code Online (Sandbox Code Playgroud)
解引用:
$ref->(@args);
&$ref;
&{$ref}(@args);
Run Code Online (Sandbox Code Playgroud)
如果$ref是一个方法(期望$self作为第一个参数)并且您想在您的上调用它$self,则语法为:
$self->$ref(@args)
Run Code Online (Sandbox Code Playgroud)
使用以下内容:
$self->$ref();
Run Code Online (Sandbox Code Playgroud)
使用此语法,$ref可以是对子例程的引用,甚至是具有要调用的方法名称的字符串,例如,
my $ref = "foo";
$self->$ref();
Run Code Online (Sandbox Code Playgroud)
请注意,这两者在继承方面的语义略有不同.
如果未传递显式参数,则括号是可选的:
$self->$ref; # also flies
Run Code Online (Sandbox Code Playgroud)
否则,请使用
$self->$ref($arg1, \%arg2, @others);
Run Code Online (Sandbox Code Playgroud)