Note that many people call Perl subroutines "functions". We prefer to use the term "functions" for those routines that are built in to Perl, and "subroutines" for code written by the Perl programmer. This is not standard terminology, so you may hear others use subroutines and functions interchangeably, but that will not be the case in this book. We feel that it is easier to make the distinction if we have two different terms for functions and subroutines.
Note that user subroutines can be used anywhere it is valid to use a native Perl function. Defining Subroutines
Defining a subroutine is quite easy. You use the keyword sub, followed by the name of your subroutine, followed by a code block. This friendly subroutine can be used to greet the user:
use strict;
sub HowdyEveryone {
print "Hello everyone.\nWhere do you want to go with Perl today?\n";
}
&HowdyEveryone;
This is very easy to do with the return statement.
use strict;
sub HowdyEveryone {
return "Hello everyone.\nWhere do you want to go with Perl today?\n";
}
print &HowdyEveryone;
At the start of each subroutine, Perl sets a special array variable, @_, to be the list of arguments sent into the subroutine. By standard convention, you can access these variables through $_[0 .. $#_]. However, it is a good idea to instead immediately declare a list of variables and assign @_ to them. For example, if we want to greet a particular group of people, we could do the following:
use strict;
sub HowdyEveryone {
my($name1, $name2) = @_;
return "Hello $name1 and $name2.\n" .
"Where do you want to go with Perl today?\n";
}
print &HowdyEveryone("bart", "lisa");
This subroutine leaves a bit to be desired. It would be nice if we could have a custom greeting, instead of just "Hello". In addition, we would like to greet as many people as we want to, not just two. This version fixes those two problems:
use strict;
sub HowdyEveryone {
my($greeting, @names) = @_;
my $returnString;
foreach my $name (@names) {
$returnString .= "$greeting, $name!\n";
}
return $returnString .
"Where do you want to go with Perl today?\n";
}
print &HowdyEveryone("Howdy", "bart", "lisa", "homer", "marge", "maggie");