Subroutines in Perl
Named subroutines (or procedures or methods) are blocks of code that can take scalar inputs and return outputs. They have the general form sub name { code; }
.
- In this example we use a subroutine to define a function.
sub fx { my $t=shift(); return 4*cos($t); }
The shift operator grabs the input to the subroutine, which is then stored in the local scalar variable $t
. This named subroutine can be used later, for example, to create an array @xcoord
of x-coordinates of points on the radius 4 circle centered at the origin.
foreach my $i (0..6) {
$xcoord[$i] = fx($i);
}
- In this example, we create a subroutine that returns the max of two numerical inputs.
sub max {
$a = shift();
$b = shift();
if ($a >= $b) {
return $a;
} else {
return $b;
}
}
max(-1,5);
- By default, the inputs to a subroutine are stored in the local array
@_
and the scalars in this array can be accessed via $_[0]
, $_[1]
, etc. We could rewrite our max subroutine as follows.
sub max {
if ($_[0] >= $_[1]) {
return $_[0];
} else {
return $_[1];
}
}
max(-1,5);
Online References