Subroutines



next up previous
Next: Packages Up: Subroutines and Packages Previous: Subroutines and Packages

Subroutines

Perl scripts can contain functions (usually called ``subs'') which have parameters and can return values. Listed below is a skeleton for a Perl sub called sub1.

sub sub1
{
      local($param1,$param2) = @_;
# do something interesting
      $value;
}

This sub can then be called in this way:

$return_val = do sub1("this is","a test");

The do can be replaced by &. This is actually the preferred method:

$return_val = &sub1("this is","a test");

There are a few thing to keep in mind when writing subroutines. Parameters are put into the array @_ inside the routine. Since all variables are global by default, we use the local() function to copy the values into local variables.

Perl has a return statement which can be used to explicitly return values. This is usually unnecessary, however, because the return value from a Perl subroutine is simply the value of the last statement executed. Thus, if you want a subroutine to return a zero, the last line of the routine can be 0;.