Learning Perl
  • Alternative view 1 of Learning Perl
  • Alternative view 2 of Learning Perl

Learning Perl

3.9 22
by Randal L. Schwartz, Tom Phoenix, brian d foy

View All Available Formats & Editions

Ask Perl programmers what source they relied on most when learning the language, and a vast majority will point to this book. Written by recognized leaders in the Perl community, this fifth edition is updated for all changes to the language up to Perl 5.10. Now designed to meet the pace and scope sought by today's programmers, the book retains the detailed


Ask Perl programmers what source they relied on most when learning the language, and a vast majority will point to this book. Written by recognized leaders in the Perl community, this fifth edition is updated for all changes to the language up to Perl 5.10. Now designed to meet the pace and scope sought by today's programmers, the book retains the detailed discussions, thorough examples, and eclectic wit that made it famous.

Editorial Reviews

The Barnes & Noble Review
Want to learn Perl? Any Perlmonger will tell you where to start -- with “the Llama book,” Learning Perl. Now’s the time: It’s just been thoroughly updated for Perl 5.8 and reorganized to be even more effective at teaching Perl novices.

No introductory guide can cover all of Perl, but Learning Perl cover all you need to get seriously productive: scalar data, lists, arrays, subroutines, I/O, hashes, control structures, strings, sorting, processes, and more. This edition’s additions include a new chapter on Perl’s invaluable CPAN archive, plus significantly improved coverage of regular expressions.

Learning Perl’s exercises have been refined through live instruction to thousands of students; they’re truly worth your time. They’ll go a long way towards helping you achieve this book’s core goal: not just to teach you Perl but to transform you into a Perl programmer. Bill Camarda, from the September 2005 Read Only

A hands-on tutorial featuring exercises and complete solutions, covering basics rather than advanced issues. Contents include Perl basics, the language's broad capabilities, brief code examples, system commands, and how to manage DBM databases using Perl. This second edition contains a new chapter on CGI programming. Annotation c. by Book News, Inc., Portland, Or.

Product Details

O'Reilly Media, Incorporated
Publication date:
Edition description:
Fifth Edition
Product dimensions:
7.00(w) x 9.00(h) x 0.90(d)

Read an Excerpt

Chapter 4: Subroutines

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.1 These let us recycle one chunk of code many times in one program.2

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.

Defining a Subroutine

To define your own subroutine, use the keyword sub, the name of the subroutine (without the ampersand), then the indented3 block of code (in curly braces) which makes up the body of the subroutine, something like this:

sub marine {
  $n += 1;  # Global variable $n
  print "Hello, sailor number $n!\n";

Subroutine definitions can be anywhere in your program text, but programmers who come from a background of languages like C or Pascal like to put them at the start of the file. Others may prefer to put them at the end of the file, so that the main part of the program appears at the beginning. It's up to you. In any case, you don't normally need any kind of forward declaration.4

Subroutine definitions are global; without some powerful trickiness, there are no private subroutines.5 If you have two subroutine definitions with the same name, the later one overwrites the earlier one.6 That's generally considered bad form, or the sign of a confused maintenance programmer.

As you may have noticed in the previous example, you may use any global variables within the subroutine body. In fact, all of the variables we've seen so far are globals; that is, they are accessible from every part of your program. This horrifies linguistic purists, but the Perl development team formed an angry mob with torches and ran them out of town years ago. We'll see how to make private variables in the section "Private Variables in Subroutines" later in this chapter.

Invoking a Subroutine

Invoke a subroutine from within any expression by using the subroutine name (with the ampersand):7

&marine;  # says Hello, sailor number 1!
&marine;  # says Hello, sailor number 2!
&marine;  # says Hello, sailor number 3!
&marine;  # says Hello, sailor number 4!

Sometimes, we refer to the invocation as calling the subroutine.

Return Values

The subroutine is always invoked as part of an expression, even if the result of the expression isn't being used. When we invoked &marine earlier, we were calculating the value of the expression containing the invocation, but then throwing away the result.

Many times, we'll call a subroutine and actually do something with the result. This means that we'll be paying attention to the return value of the subroutine. All Perl subroutines have a return value--there's no distinction between those that return values and those that don't. Not all Perl subroutines have a useful return value, however.

Since all Perl subroutines can be called in a way that needs a return value, it'd be a bit wasteful to have to declare special syntax to "return" a particular value for the majority of the cases. So Larry made it simple. Every subroutine is chugging along, calculating values as part of its series of actions. Whatever calculation is last performed in a subroutine is automatically also the return value.

For example, let's define this subroutine:

sub sum_of_fred_and_barney {
  print "Hey, you called the sum_of_fred_and_barney subroutine!\n";
  $fred + $barney;  # That's the return value

The last expression evaluated in the body of this subroutine is the sum of $fred and $barney, so the sum of $fred and $barney will be the return value. Here's that in action:

$fred = 3;
$barney = 4;
$c = &sum_of_fred_and_barney; # $c gets 7
print "\$c is $c.\n";
$d = 3 * &sum_of_fred_and_barney; # $d gets 21
print "\$d is $d.\n";

That code will produce this output:

Hey, you called the sum_of_fred_and_barney subroutine!
$c is 7.
Hey, you called the sum_of_fred_and_barney subroutine!
$d is 21.

That print statement is just a debugging aid, so that we can see that we called the subroutine. You'd take it out when the program is finished. But suppose you added another line to the end of the code, like this:

sub sum_of_fred_and_barney {
  print "Hey, you called the sum_of_fred_and_barney subroutine!\n";
  $fred + $barney;  # That's not really the return value!
  print "Hey, I'm returning a value now!\n"; # Oops!

In this example, the last expression evaluated is not the addition; it's the print statement. Its return value will normally be 1, meaning "printing was successful,"8 but that's not the return value we actually wanted. So be careful when adding additional code to a subroutine to ensure that the last expression evaluated will be the desired return value.

So, what happened to the sum of $fred and $barney in that subroutine? We didn't put it anywhere, so Perl discarded it. If you had requested warnings, Perl (noticing that there's nothing useful about adding two variables and discarding the result) would likely warn you about something like "a useless use of addition in a void context." The term void context is just a fancy of saying that the answer isn't being stored in a variable or used by another function.

"The last expression evaluated" really means the last expression evaluated, rather than the last line of text. For example, this subroutine returns the larger value of $fred or $barney:

sub larger_of_fred_or_barney {
  if ($fred > $barney) {
  } else {

The last expression evaluated is the single $fred or $barney, which becomes the return value. We won't know whether the return value will be $fred or $barney until we see what those variables hold at runtime.

A subroutine can also return a list of values when evaluated in a list context.9 Suppose you wanted to get a range of numbers (as from the range operator, ..), except that you want to be able to count down as well as up. The range operator only counts upwards, but that's easily fixed:

sub list_from_fred_to_barney {
  if ($fred < $barney) {
    # Count upwards from $fred to $barney
  } else {
    # Count downwards from $fred to $barney
    reverse $barney..$fred;
$fred = 11;
$barney = 6;
@c = &list_from_fred_to_barney; # @c gets (11, 10, 9, 8, 7, 6)

In this case, the range operator gives us the list from 6 to 11, then reverse reverses the list, so that it goes from $fred (11) to $barney (6), just as we wanted.

These are all rather trivial examples. It gets better when we can pass values that are different for each invocation into a subroutine instead of relying on global variables. In fact, that's coming right up.


That subroutine called larger_of_fred_or_barney would be much more useful if it didn't force us to use the global variables $fred and $barney. That's because, if we wanted to get the larger value from $wilma and $betty, we currently have to copy those into $fred and $barney before we can use larger_of_fred_or_barney. And if we had something useful in those variables, we'd have to first copy those to other variables, say $save_fred and $save_barney. And then, when we're done with the subroutine, we'd have to copy those back to $fred and $barney again.

Luckily, Perl has subroutine arguments. To pass an argument list to the subroutine, simply place the list expression, in parentheses, after the subroutine invocation, like this:

$n = &max(10, 15);  # This sub call has two parameters

That list is passed to the subroutine; that is, it's made available for the subroutine to use however it needs to. Of course, this list has to be stored into a variable, so the parameter list (another name for the argument list) is automatically assigned to a special array variable named @_ for the duration of the subroutine. The subroutine can access this variable to determine both the number of arguments and the value of those arguments.

So, that means that the first subroutine parameter is stored in $_[0], the second one is stored in $_[1], and so on. But--and here's an important note--these variables have nothing whatsoever to do with the $_ variable, any more than $dino[3] (an element of the @dino array) has to do with $dino (a completely distinct scalar variable). It's just that the parameter list must be stored into some array variable for the subroutine to use it, and Perl uses the array @_ for this purpose.

Now, you could write the subroutine &max to look a little like the subroutine &larger_of_fred_or_barney, but instead of using $a you could use the first subroutine parameter ($_[0]), and instead of using $b, you could use the second subroutine parameter ($_[1]). And so you could end up with code something like this:

sub max {
  # Compare this to &larger_of_fred_or_barney
  if ($_[0] > $_[1]) { 
  } else {

Well, as we said, you could do that. But it's pretty ugly with all of those subscripts, and hard to read, write, check, and debug, too. We'll see a better way in a moment.

There's another problem with this subroutine. The name &max is nice and short, but it doesn't remind us that this subroutine works properly only if called with exactly two parameters:

$n = &max(10, 15, 27);  # Oops!

Excess parameters are ignored--since the subroutine never looks at $_[2], Perl doesn't care whether there's something in there or not. And insufficient parameters are also ignored--you simply get undef if you look beyond the end of the @_ array, as with any other array. We'll see how to make a better &max, which works with any number of parameters, later in this chapter.

The @_ variable is local to the subroutine;10 if there's a global value in @_, it is saved away before the subroutine is invoked and restored to its previous value upon return from the subroutine.[11] This also means that a subroutine can pass arguments to another subroutine without fear of losing its own @_ variable--the nested subroutine invocation gets its own @_ in the same way. Even if the subroutine calls itself recursively, each invocation gets a new @_, so @_ is always the parameter list for the current subroutine invocation.

Private Variables in Subroutines

But if Perl can give us a new @_ for every invocation, can't it give us variables for our own use as well? Of course it can.

By default, all variables in Perl are global variables; that is, they are accessable from every part of the program. But you can create private variables called lexical variables at any time with the my operator:

sub max {
  my($a, $b);       # new, private variables for this block
  ($a, $b) = @_;    # give names to the parameters
  if ($a > $b) { $a } else { $b }

These variables are private (or scoped) to the enclosing block; any other $a or $b is totally unaffected by these two. And that goes the other way, too--no other code can access or modify these private variables, by accident or design.12 So, we could drop this subroutine into any Perl program in the world and know that we wouldn't mess up that program's $a and $b (if any).13

It's also worth pointing out that, inside the if's blocks, there's no semicolon needed after the return value expression. Although Perl allows for the last semicolon in a block to be omitted, in practice that's omitted only when the code is so simple that the block is written in a single line, like the previous ones.

The subroutine in the previous example could be made even simpler. Did you notice that the list ($a, $b) was written twice? That my operator can also be applied to a list of variables enclosed in parentheses, so it's more customary to combine those first two statements in the subroutine...

Meet the Author

Randal Schwartz coauthored the "must-have" standards: Programming Perl, Learning Perl, Learning Perl for Win32 Systems, and Effective Perl Programming, and writes regular columns for WebTechniques, PerformanceComputing, SysAdmin, and Linux magazines. He's a frequent contributor to the Perl newsgroups, and has moderated comp.lang.perl.announce since its inception. Randal's desire to give back to the Perl community inspired him to help create and provide initial funding for The Perl Institute. He is a founding board member of the Perl Mongers (perl.org), the worldwide Perl grassroots advocacy organization. Since 1985, Randal has owned and operated Stonehenge Consulting Services, Inc.

Tom Phoenix has worked in the field of education since 1982 and has taught Perl classes for Stonehenge Consulting Services since 1996. He answers many of the questions on the comp.lang.perl.* newsgroups and contributes to the development and usefulness of Perl.

Customer Reviews

Average Review:

Write a Review

and post it to your social network


Most Helpful Customer Reviews

See all customer reviews >

Learning Perl 3.8 out of 5 based on 0 ratings. 19 reviews.
Runey676 More than 1 year ago
This is the best book for learning Perl, in my opinion. This might not be the best book those who haven't ever programed before though because it focuses more on the syntax of the simple things (like if, while, for, etc.) and expects you know how they work. What I liked about this book was all the footnotes. Yes, I know that sounds weird, but there are a lot of footnotes, all with interesting information, like why Larry named things the names he did. Overall, this books keeps you interested, and isn't a long boring read.
Guest More than 1 year ago
If you want to spend some time learning Perl, this fourth edition of the book is for you. Authors Randal Schwartz, Tom Phoenix and brian foy, have done an outstanding job of providing you with a book that helps you understand why the Perl programming language is the workhorse of the Internet as well as, the language of choice for system administrators, web hackers, and casual programmers around the world. Schwartz, Phoenix and foy begin by asking you a number of questions: What does Perl stand for? How can you get Perl? How do you make a Perl program? And, so forth. Next, the authors cover scalar data, with respect to numbers and strings. Then, they examine lists (an ordered collection of scalars) and arrays ( a variable that contains a list). The authors continue by showing you how Perl can make subrountines, which are user-defined functions. In addition, the authors next introduce you to the workings of standard input, output and error streams. They also show you a feature that makes Perl one of the world's great programming languages--hashes. Next, the authors take you on a trip to visit the world of regular expressions, where you can forget about the world of Perl. Then, they show you where this world fits into Perl's world. The authors continue by showing you how to use patterns to locate the parts of strings that you want to change. Then, you'll see some alternative ways to write Perl code. In addition, the authors present a complete set of tests that are used by Perl to help you find information about files. They also show you how Perl lets you manipulate operations directories directly, in ways that are even fairly portable from one operating system to another. Next, the authors show you a simpler way of working with strings and sorting. Then, they present the inner workings of process management. The authors continue by showing you how to use modules that already exist. Finally, they examine some advanced Perl techniques. With the preceding in mind, the authors have done an excellent job of giving you a real whirlwind tour of Perl. So, at the end of the day, you'll know whether this is the right Perl book for you!
Anonymous More than 1 year ago
Michael Hall More than 1 year ago
Code examples run off the edge of the screen so you cannot read them. Read it in another form because it is worth reading. It is a good intro to Perl from the ground up.
Anonymous More than 1 year ago
TEST NOOKUSER More than 1 year ago
constant width text does not reflow properly. this makes the majority of the comments in code examples partially unreadable where they run off the page. content of the book is otherwise great.
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Random_Geek More than 1 year ago
This book is an excellent intro to Perl. It will also serve as a reference later on. Highly recommended purchase if you have any interest in Perl
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Anonymous More than 1 year ago
Guest More than 1 year ago
This is a wonderful book for any beginner to Perl. I'd had no previous experience, and I've found the exercises to be easy and educational. The authors have good senses of humor and the writing style is excellent. Overall, 'Learning Perl' is a must-have for all beginning Perl students.
Anonymous More than 1 year ago