How to write a function link in a Perl module?

I am trying to figure out how to make a function reference for a Perl module. I know how to do this outside the module, but inside one? Consider the following code:

==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 is the correct syntax for (1) defining a function reference in the first place and (2) dereferencing it?

+6
perl
source share
3 answers

TMTOWTDI

Defining a function reference:

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

Dereferencing:

 $ref->(@args); &$ref; &{$ref}(@args); 
+20
source share

If $ref is a method (expects $self as the first argument), and you want to call it your $self , the syntax is:

 $self->$ref(@args) 
+8
source share

Use the following:

 $self->$ref(); 

Using this syntax, $ref can be a reference to a subroutine or even to a line with the name of the method to call, for example,

 my $ref = "foo"; $self->$ref(); 

Keep in mind that they have slightly different semantics regarding inheritance.

If you do not pass explicit arguments, brackets are optional:

 $self->$ref; # also flies 

Otherwise use

 $self->$ref($arg1, \%arg2, @others); 
+6
source share

All Articles