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?
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)
TMTOWTDI
Defining a function reference:
$ref = \&subroutine;
$ref = sub { BLOCK };
$ref = "subroutineName"; # or $ref = $scalarSubroutineName
Dereferencing:
$ref->(@args);
&$ref;
&{$ref}(@args);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With