Like most other programming languages, perl has subroutines, too. They are kind of strange, but still easy to learn. The handling of parameters and return values however is new: all functions get their parameters as one single flat list of scalars, and likewise they return to their caller one single flat list of scalar values. Any arrays or hashes in these call- and return-lists will collapse, losing their identities, but since perl knows only calls by reference , this is no problem at all.
The following example is a simple function which gets two values and returns the sum of them:
sub add {
my($a, $b) = @_;
return $a + $b;
}
Note that there is no formal list of parameters. They are all passed
to the function in the flat list @_
. As mentioned before, there is only a call
by reference, but a call by value can
be done, if the parameter list is assigned to locally defined variables
using the instruction my. In perl all functions have a return
value. If the return statement is omitted, the
variable $_ is automatically used. But like in C,
it is not forced to use this return value. The following function is
equivalent to the one just given:
sub add {
$_[0] + $_[1];
}