Chapter 8. Dynamic Subroutines
For the purposes of this chapter, I’m going to label as “dynamic subroutines” anything I don’t explicitly
name by typing sub some_name
or that
doesn’t exist until runtime. Perl is extremely flexible in letting me figure
out the code as I go along, and I can even have code that writes code. I’m
going to lump a bunch of different subroutine topics in this chapter just
because there’s no good home for them apart from each other.
We first showed anonymous subroutines in Learning
Perl when we showed user-defined sorting, although we didn’t
tell you that they were anonymous subroutines. In Intermediate
Perl we used them to create closures, work with map
and grep
,
and do a few other things. I’ll pick up where Intermediate
Perl left off to show just how powerful they can be. With any of
these tricks, not knowing everything ahead of time can be very
liberating.
Subroutines as Data
I can store anonymous subroutines in variables. They don’t actually
execute until I tell them to. Instead of storing values, I store behavior.
This anonymous subroutine adds its first two arguments and returns the
result, but it won’t do that until I execute it. I merely define the
subroutine and store it in $add_sub
:
my $add_sub = sub { $_[0] + $_[1] };
This way, I can decide what to do simply by choosing the variable
that has the behavior that I want. A simple-minded program might do this
with a series of if-elsif
tests and branches because it needs to hardcode a branch for each possible ...
Get Mastering Perl, 2nd Edition 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.