Chapter 8. Functions

We’ve already seen and used predetermined, built-in functions, such as chomp, print, and so on. Now, let’s take a look at functions that you define yourself.

Defining a User Function

A user function, more commonly called a subroutine or just a sub, is defined in your Perl program using a construct like:

            sub subname {
		statement_1;
		statement_2;
		statement_3;
}

The subname is the name of the subroutine, which is like the names we’ve had for scalar variables, arrays, and hashes. Once again, these come from a different namespace, so you can have a scalar variable $fred, an array @fred, a hash %fred, and now a subroutine fred.[56]

The block of statements following the subroutine name becomes the definition of the subroutine. When the subroutine is invoked (described shortly), the block of statements that makes up the subroutine is executed, and any return value (described later) is returned to the caller.

Here, for example, is a subroutine that displays that famous phrase:

sub say_hello {
		print "hello, world!\n";
}

Subroutine definitions can be anywhere in your program text (they are skipped on execution), but we like to put them at the end of the file, so that the main part of the program appears at the beginning of the file. (If you like to think in Pascal terms, you can put your subroutines at the beginning and your executable statements at the end, instead. It’s up to you.)

Subroutine definitions are global;[57] there are no local subroutines. If you have two subroutine ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.