The Perl Tutorial: What's Perl?(4)

Functions

Functions are used to organize your code into small pieces which can be reused. Perl declares functions using the sub keyword followed by the { sign to start the function and the } to end it:


sub function1 {
CODE HERE
}

In order to call a Perl function it's suggested that you call it using the & sign followed by the function name. If you have parameters, they can be also passed, so it's suggested that you enclose them in parentheses:

&function1;

In Perl, functions can serve as procedures which do not return a value (in reality they do, but that will be discussed later), or functions which do return a value. The above example is of a function that acts as a procedure. Below is an example of a function that acts as a function, because it returns a value (we are also passing values to the function):

$answer = &add(1,2);

You aren't limited to passing only scalar values to a function. You can also pass it arrays, but it will be easier to pass them at the end.

Perl functions receive their values in an array: @_

This array holds all the values of the parameters passed to the function. So in the above example, where we had 2 values passed, we would retrieve them in the following manner:


sub function1 {
($val1, $val2) = @_;
}

or we could do it in this manner:


sub function1 {
$val1=$_[0];
$val2=$_[1];
}

The parameters are being passed by value, meaning that you will be working with copies of the original parameters and not the actual parameters themselves. If you wish to pass them by reference, then you would have to work directly with the variable ($_[subscript]).

Perl's scope of variables is different than most other languages. You don't have to declare your variables at the beginning of the program, or in the functions: you just use them. The scope of the variables is always global. If you use a variable in a function, it is global to the rest of the program. If you want the variable to be seen only by code within that particular function (and any other functions it may call), then you must declare it as a local variable:


sub function1 {
local($myvar)
}

The above code will declare $myvar as local, so it can't be seen by the rest of the program.

Functions can also be nested within each other, and you can create recursive functions that call themselves.

Control Statements