We have already learned how to use built-in functions. Now let us learn how to define our own functions.

Function Definition

A user-defined function (or subroutine) has the following structure:
sub subroutine_name {
You may place subroutines anywhere inside a Perl program, but for clarity it is recommended to place them at the end of the file.

Function Name

Function names should follow the same rules as variable names. Namely, they should begin with a letter, and then they may have any number of letters, numbers and underscores (_).

You may use in the same program a variable named $a, another variable named @a and a subroutine named a and they will mean different things. (Of course, this is confusing and not recommended...)

Function Invocation

To invoke the subroutine from your Perl program, you write the subroutine name followed by parentheses. This will cause execution of the block of statements enclosed by the subroutine's definition curly brackets.

subroutine_name ();

Subroutines may also be invoked from within other subroutines.

Table of Contents.