Chapter 6. Subroutines
Like many languages, Perl provides for user-defined
subroutines.[1] These subroutines may be defined anywhere in the main
program, loaded in from other files via the do,
require, or use keywords, or
generated at run time using eval. You can even load
them at run time with the mechanism described in Section 10.2 in Chapter 10. You can call a subroutine
indirectly, using a variable containing either its name or a reference
to the routine, or through an object, letting the object determine which
subroutine should really be called. You can generate anonymous
subroutines, accessible only through references, and if you want, use
these to clone new, nearly identical functions via
closures, which are covered in the section by that
name in Chapter 8.
Syntax
To declare a named subroutine without defining it, use one of these forms:
subNAMEsubNAMEPROTOsubNAMEATTRSsubNAMEPROTOATTRS
To declare and define a named subroutine, add a
BLOCK:
subNAMEBLOCKsubNAMEPROTOBLOCKsubNAMEATTRSBLOCKsubNAMEPROTOATTRSBLOCK
To create an anonymous subroutine or closure, leave out
the NAME:
subBLOCKsubPROTOBLOCKsubATTRSBLOCKsubPROTOATTRSBLOCK
PROTO and
ATTRS stand for the prototype and
attributes, each of which is discussed in its own section later in the
chapter. They're not so important--the NAME
and the BLOCK are the essential parts, even
when they're missing.
For the forms without a
NAME, you still have to provide some way of calling the subroutine. So be ...