8.1. 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 this:

sub subname {
    statement_1;
    statement_2;
    statement_3;
}

The subname is the name of the subroutine, which is any name 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.[1]

[1] Technically, the subroutine's name is &fred, but you seldom need to call it that.

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;[2] there are no local subroutines. If you have two subroutine definitions with the same name, the later one overwrites the earlier ...

Get Learning Perl, Second Edition 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.