Writing subroutines
Writing subroutines is easy:
sub log {
my $logmessage = shift;
print LOGFILE $logmessage;
}
What's that "shift"? Well, the arguments to a subroutine are available
to us as a special array called @_ (see perlvar for more on that). The
default argument to the "shift" function just happens to be @_. So "my
$logmessage = shift;" shifts the first item off the list of arguments
and assigns it to $logmessage.
We can manipulate @_ in other ways too:
my ($logmessage, $priority) = @_; # common
my $logmessage = $_[0]; # uncommon, and ugly
Subroutines can also return values:
sub square {
my $num = shift;
my $result = $num * $num;
return $result;
}
For more information on writing subroutines, see perlsub.
|