O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required