How to write a function reference in a Perl module?
I'm trying to figure out how to make a function reference work for a Perl module. I know how to do it outside of a module, but inside one? Consider code like this:
==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===
Look 开发者_开发百科at lines 5-6 above. What's the correct syntax for (1) defining the function reference in the first place, and (2) dereferencing it?
TMTOWTDI
Defining a function reference:
$ref = \&subroutine;
$ref = sub { BLOCK };
$ref = "subroutineName"; # or $ref = $scalarSubroutineName
Dereferencing:
$ref->(@args);
&$ref;
&{$ref}(@args);
If $ref
is a method (expects $self
as first argument) and you want to call it on
your $self
, the syntax is:
$self->$ref(@args)
Use the following:
$self->$ref();
With this syntax, $ref
can be a reference to a subroutine or even a string with the name of the method to call, e.g.,
my $ref = "foo";
$self->$ref();
Be aware that the two have slightly different semantics with respect to inheritance.
When you aren't passing explicit arguments, the parentheses are optional:
$self->$ref; # also flies
Otherwise, use
$self->$ref($arg1, \%arg2, @others);
精彩评论