Taking References to Functions
Problem
You need to manipulate a subroutine by reference. This might happen if you need to create a signal handler, a Tk callback, or a hash of function pointers.
Solution
To get a code reference:
$cref = \&func; $cref = sub { ... };
To call a code reference:
@returned = $cref->(@arguments); @returned = &$cref(@arguments);
Discussion
If the name of a function is func
, you can produce
a reference to this code by preceding that name with
\&
. You can also create anonymous functions
using the sub
{}
notation.
These code references can be stored just like any other reference.
Perl 5.004 introduced the postfix arrow notation for dereferencing a
code reference. Prior to that, to call a subroutine by reference, you
had to say &$funcname(@ARGS)
, where
$funcname
contained the name of a function.
Although it is still possible to store the name of a function in a
variable, such as:
$funcname = "thefunc"; &$funcname();
that’s not a very good solution for several reasons. First, it
uses symbolic references, not real (hard) references, so it is
forbidden under the use
strict
'refs'
pragma. Symbolic references to
variables are usually a bad idea, since they can’t access
lexical variables, only globals, and aren’t reference counted.
Second, it doesn’t include package information, so if executed in a different package, it would try to call the wrong function. Finally, in the odd case that the function were redefined at some point, the symbolic reference would get whatever the ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.