start page | rating of books | rating of authors | reviews | copyrights

Perl Cookbook

Perl CookbookSearch this book
Previous: 9.12. Program: lst Chapter 10 Next: 10.1. Accessing Subroutine Arguments
 

10. Subroutines

Contents:
Introduction
Accessing Subroutine Arguments
Making Variables Private to a Function
Creating Persistent Private Variables
Determining Current Function Name
Passing Arrays and Hashes by Reference
Detecting Return Context
Passing by Named Parameter
Skipping Selected Return Values
Returning More Than One Array or Hash
Returning Failure
Prototyping Functions
Handling Exceptions
Saving Global Values
Redefining a Function
Trapping Undefined Function Calls with AUTOLOAD
Nesting Subroutines
Program: Sorting Your Mail

Composing mortals with immortal fire.

- W. H. Auden "Three Songs for St Cecilia's Day"

10.0. Introduction

To avoid the dangerous practice of copying and pasting code throughout a program, your larger programs will probably reuse chunks of code with subroutines. We'll use the terms subroutine and function interchangeably, because Perl doesn't distinguish between the two any more than C does. Even object-oriented methods are just subroutines that are called using a special syntax, described in Chapter 13, Classes, Objects, and Ties .

A subroutine is declared with the sub keyword. Here's a simple subroutine definition:

sub hello {      $greeted++;          # global variable      print "hi there!\n"; }

The typical way of calling that subroutine is:

hello();                 # call subroutine hello with no arguments/parameters

Because Perl compiles your program before executing it, it doesn't matter where your subroutines are declared. These definitions don't have to be in the same file as your main program. They can be pulled in from other files using the do , require , or use operators, as described in Chapter 12, Packages, Libraries, and Modules . They can even be created on the fly using eval or the AUTOLOAD mechanism, or generated using closures, which can be used as function templates.

If you are familiar with other programming languages, several characteristics of Perl's functions may surprise you if you're not prepared. Most of the recipes in this chapter illustrate how to take advantage of  - and be aware of  - these properties.

Calling a function as $x = &func; does not supply any arguments, but rather provides direct access to its caller's @_ array! If you omit the ampersand and use either func() or func , then a new and empty @_ is provided instead.


Previous: 9.12. Program: lst Perl Cookbook Next: 10.1. Accessing Subroutine Arguments
9.12. Program: lst Book Index 10.1. Accessing Subroutine Arguments

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.