next up previous
Next: Some Example Perl Scripts Up: Some useful Perl Previous: Reading and Writing Files

Subroutines or functions

We have actually been using Perl and cgi-lib.pl subroutine or functions from the start. We will know look at how we develop our own.

Subroutine are useful in breaking up or programs into smaller more manageable pieces that make program development and maintenance much easier.

A subroutine in Perl is defined as follows:

sub subname {
     statement_1;
     statement_2;
     ........
     statement_n;
}

Subroutine names can be any usual name as used for scalars, arrays etc.

Subroutines are always referred to by a & in Perl.

You can supply arguments to a subroutine: They are passed in as a list and referred to by the $_ list within the subroutine body.

For example to add to number together in Perl we may call a function sum

$a = 3;
$b = 4;
$c = &sum($a,$b);

The subroutine may be written as follows:

sub sum {
  $_[0] + $_[1];
}

The value of the expression is $_[0] + $_[1] is the returned value.



Dave Marshall
9/28/2001