Chapter 4. Subroutines
You’ve seen and used some of the built-in system functions, such as chomp, reverse, and print. But, as other languages do, Perl has the ability to make subroutines
, which are user-defined functions.[90] These let us recycle one chunk of code many times in one program.[91] The name of a subroutine is another Perl identifier (letters, digits, and underscores, but it can’t start with a digit) occasionally with an optional ampersand (&) in front. There’s a rule about when you can omit the ampersand and when you cannot; you’ll see that rule by the end of the chapter. For now, we’ll use it every time it’s allowed, which is always a safe rule. We’ll tell you every place where it’s forbidden, of course.
The 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, though 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), and the indented block of code (in curly braces)[92] that 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 such as C or Pascal like to put them at the start of the file. Others may prefer to put them at the end of the ...
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.
Read now
Unlock full access