Using Subroutine References
Let’s look at some common examples of using subroutine references: callback functions and higher-order procedures.
A callback function is an ordinary subroutine whose reference is passed around. The caller (who uses that reference) doesn’t necessarily have an idea of which subroutine is getting invoked. Let’s examine three simple examples involving callback functions: dispatch tables, signal handlers, and plotting functions.
Dispatch Table
A typical
dispatch
table is an array of subroutine references. The following example
shows %options as a dispatch table that maps a set
of command-line options to different subroutines:
%options = ( # For each option, call appropriate subroutine.
"-h" => \&help,
"-f" => sub {$askNoQuestions = 1},
"-r" => sub {$recursive = 1},
"_default_" => \&default,
);
ProcessArgs (\@ARGV, \%options); # Pass both as referencesSome of these references in this code are to named subroutines.
Others don’t do much, so it is just simpler to code them as
inline, anonymous subroutines. ProcessArgs can now
be written in a very generic way. It takes two arguments: a reference
to an array that it parses and a mapping of options that it refers to
while processing the array. For each option, it calls the appropriate
“mapped” function, and if an invalid flag is supplied in
@ARGV, it calls the function corresponding to the
string _default_.
ProcessArgs is shown in Example 4.1.
Example 4-1. ProcessArgs
ProcessArgs (\@ARGV, \%options); # Pass both as ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access