[Chapter 8] Functions
Author: Randal L. Schwartz, Erik Olson & Tom Christiansen
Date: 1999-07-02T01:33:55Z

#

| Chapter 8 |

# 8. Functions

Contents:
Defining a User Function
Invoking a User Function
Return Values
Arguments
Private Variables in Functions
Semiprivate Variables Using local
File-Level my( ) Variables
Exercises

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.

## 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:

    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`.[1]

> [1] Technically, the subroutine's name is `&fred`, but you seldom need to call it that. See Chapter 2 of Programming Perl for all of the gory details.

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 one without warning.[3]

> [2] They are global to the current package, actually, but since this book doesn't really deal with separate packages, you may think of subroutine definitions as global to the whole program.

> [3] This statement is true, unless you are running with the `-w` switch.

Within the subroutine body, you may access or give values to variables that are shared with the rest of the program (a global variable). In fact, by default, any variable reference within a subroutine body refers to a global variable. We'll tell you about the exceptions in the later section entitled "Private Variables in Functions." In the following example:

    sub say_what {
      print "hello, $what\n";
    }

`$what` refers to the the global `$what`, which is shared with the rest of the program.

7.7 Exercises |  | 8.2 Invoking a User Function