Learning Perl

Learning PerlSearch this book
Previous: 7.7 ExercisesChapter 8Next: 8.2 Invoking a User Function
 

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 built-in functions, such as chomp, print, and so on. Now, let's take a look at functions that you define for 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 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 one without warning.[3]

[2] 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] 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 upcoming section "Private Variables in Functions." In the following example,

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

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


Previous: 7.7 ExercisesLearning PerlNext: 8.2 Invoking a User Function
7.7 ExercisesBook Index8.2 Invoking a User Function