Skip to Main Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced content levelIntermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

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

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.
Start your free trial

You might also like

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes
Perl in a Nutshell, 2nd Edition

Perl in a Nutshell, 2nd Edition

Nathan Patwardhan, Ellen Siever, Stephen Spainhour

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata