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:

sub NAME
sub NAME PROTO
sub NAME       ATTRS
sub NAME PROTO ATTRS

To declare and define a named subroutine, add a BLOCK:

sub NAME             BLOCK
sub NAME PROTO       BLOCK
sub NAME       ATTRS BLOCK
sub NAME PROTO ATTRS BLOCK

To create an anonymous subroutine or closure, leave out the NAME:

sub                  BLOCK
sub      PROTO       BLOCK
sub            ATTRS BLOCK
sub      PROTO ATTRS BLOCK

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

Get Programming Perl, 3rd 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.