We will now look at functions. Functions are used to organize your code into small pieces which can be re-used. Perl declares function using the sub keyword followed by the { sign to start the function and the } to end it :
sub function1{
CODE
}
In order to call a perl function it is suggested that you call it using the & sign followed by the function name. If you have parameters, they can be also passed, it is suggested that you enclose them in parenthesis:
&function1;
In perl functions can server 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 are not 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 its variables is somewhat different than most other languages, you do not 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 is a function it is global to the rest of the program. If you want the variable to be seen only the function and any function your function calls then you have to declare it local:
sub function1{
local($myvar)
}
The above code will declare $myvar as local, meaning that it cannot be seen by the rest of the program.
Functions call also be nested within each other, and you can have recursive functions, meaning functions that call themselves.
![]() |
![]() |
![]() |