Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function reference in a Perl module?

Tags:

perl

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?

like image 838
Stephen Gross Avatar asked Feb 04 '10 16:02

Stephen Gross


2 Answers

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)
like image 151
Randal Schwartz Avatar answered Oct 23 '22 14:10

Randal Schwartz


TMTOWTDI

Defining a function reference:

$ref = \&subroutine;
$ref = sub { BLOCK };
$ref = "subroutineName"; # or $ref = $scalarSubroutineName

Dereferencing:

$ref->(@args);
&$ref;  
&{$ref}(@args);
like image 27
mob Avatar answered Oct 23 '22 13:10

mob