home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeLearning Perl, 3rd EditionSearch this book

Chapter 4. Subroutines

4.1. System and User Functions

We've already seen and used some of the builtin system functions, such as chomp, reverse, print, and so on. But, as other languages do, Perl has the ability to make subroutines, which are user-defined functions.[97] These let us recycle one chunk of code many times in one program.[98]

[97]In Perl, we don't generally make the distinction that Pascal programmers are used to, between functions, which return a value, and procedures, which don't. But a subroutine is always user-defined, while a function may or may not be. That is, the word function may be used as a synonym for subroutine, or it may mean one of Perl's builtin functions. That's why this chapter is titled Subroutines, because it's about the ones you can define, not the builtins. Mostly.

[98]The code examples used in this book are recycled from at least 40% post-consumer programming, and are at least 75% recyclable into your programs when properly decomposed.

The name of a subroutine is another Perl identifier (letters, digits, and underscores, but can't start with a digit) with a sometimes-optional ampersand (&) in front. There's a rule about when you can omit the ampersand and when you cannot; we'll see that rule by the end of the chapter. For now, we'll just use it every time that it's not forbidden, which is always a safe rule. And we'll tell you every place where it's forbidden, of course.

That subroutine name comes from a separate namespace, so Perl won't be confused if you have a subroutine called &fred and a scalar called $fred in the same program -- although there's no reason to do that under normal circumstances.

Library Navigation Links

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