All the Perl programs that we have written until now simply have a set of instructions,
line by line. Like any other language, Perl allow us to write code in the modular form.
A D V E R T I S E M E N T
To do so the language should allow the programmer to set aside subroutines of
code so that they can be reused. Perl also do provide this feature.
Note here that many people do call Perl subroutines as "functions". In this section we prefer using term
"functions" for those subroutines which are built into Perl, and "subroutines" for those code
which are written by the Perl programmer.
Note here that a user subroutines can be used wherever it is valid using a native Perl
function.
Defining a Subroutine
We dont want our new subroutine to print the message. Instead,
we want it to return the string of the message, and later on we call print
on it.
use strict;
sub HelloEveryone {
return "Hello everyone.\nWhere do you want to go with Perl today?\n";
}
print &HelloEveryone;
Using Arguments in Subroutines
If you cannot give input to subroutine then that subrioutine is not of much good use.
Therefore Perl allows us to pass arguments to subroutines just like native Perl
functions.
Perl sets a special array variable "@_" at the beginning of each subroutine, to be
the list of arguments sent to the subroutine. By some standard convention, we can
access these variables using $_[0 .. $#_]. However, it is better to
declare a list of variables and assign @_ to them instead immediately. Let us consider
for example, if we want to greet particular group of people, we can do the following:
use strict;
sub HelloEveryone {
my($name1, $name2) = @_;
return "Hello $name1 and $name2.\n" .
"Where do you want to go with Perl today?\n";
}
print &HelloEveryone("John", "David");
Note here that since we are in a new block and have used my, the variables we declared
will live as long as the subroutine gets executed.
This subroutine leaves a bit that is desired. It would be good if we have a custom
greeting, instead of "Hello". In addition, we also want to greet as many people as
we want to, and not just two. This code fixes these two problems:
use strict;
sub HelloEveryone {
my($greeting, @names) = @_;
my $returnString;
foreach my $name (@names) {
$returnString .= "$greeting, $name!\n";
}
In this example we have used two interesting techniques. Firstly, we use a list as the
last parameter when we do accept arguments. It means that everything will be put into @names
after the first argument. Note here that any other variables that followed @names,
would have remained undefined. However, scalar variables before the array (like $greeting)
receive values out of @_. Thus, it is a good practice to make only array the
last argument.