Prototypes
Perl lets you define your own functions to be called like Perl’s
built-in functions. Consider push(@array,
$item), which must tacitly receive a reference to @array, not just the list values held in
@array, so that the array can be
modified. Prototypes let you declare subroutines
to take arguments just like many of the built-ins―that is, with
certain constraints on the number and types of arguments. We call them
“prototypes”, but they work more like automatic templates for the
calling context than like what C or Java programmers would think of as
prototypes. With these templates, Perl will automatically add implicit
backslashes, or calls to scalar, or
whatever else it takes to get things to show up in a way that matches
the template. For instance, if you declare:
sub mypush (+@);
then mypush takes arguments
exactly like push does. For this to
work, the declaration of the function to be called must be visible at
compile time. The prototype only affects the interpretation of
function calls when the &
character is omitted. In other words, if you call it like a built-in
function, it behaves like a built-in function. If you call it like an
old-fashioned subroutine, then it behaves like an old-fashioned
subroutine. The & suppresses
prototype checks and associated contextual effects.
Because prototypes are taken into consideration only at compile
time, it naturally falls out that they have no influence on subroutine
references like \&foo or on
indirect subroutine calls like &{$subref} ...
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