Functions, aka subroutines are blocks of code that you can call in different places and contexts. Subroutines can take arguments, and can return results. Perl has many functions already built in. You can also define your own.
Example: Return the length of the hypotenuse of a right triangle
sub hypotenuse {
my ($a,$b) = @_;
return sqrt($a**2 + $b**2);
}
sub E {
return 2.71828182845905;
}
$x = hypotenuse(3,4);
# yields 5
$x = hypotenuse(9,12);
# yields 15 |
Unlike built-in functions, you need to use parentheses with user-defined functions, even if there are no arguments to pass:
$x = hypotenuse(3,4); $y = E();
The structure of a subroutine is shown here:
sub subroutine name {
my ($arg1,$arg2,...) = @_; # copy args into local variables (optional)
Any code you like
return function result # return subroutine result (optional)
} |
If you have only a few arguments, you can use shift to obtain the arguments, one at a time:
# same as the previous example
sub hypotenuse {
my $a = shift;
my $b = shift;
return sqrt($a**2 + $b**2);
} |
Any variables that you use in a subroutine should be made local with the my operator. This avoids accidentally overwriting similarly-named variables in the main program.
Variables made local with my only exist within a block (curly braces). The subroutine body is a block, so the local variables only exist within the body of the subroutine.
You can make scalars, arrays and hashes local. If you apply my() to a list, it makes each member of the list local.
{ # start a block
my $scalar; # $scalar is local
my @array; # now @array is local
my %hash; # %hash is local
# same thing, but in one swell foop
my ($scalar,@array,%hash);
} |
|
| Contents |
Next |