Perl Subroutine
Define and call subroutine
Like other computer programming languages, Perl allows you to write your own user-defined function which is called subroutine. Subroutine allows you to reuse a chunk of code in program over and over again. You can place subroutine anywhere in program but it is recommended that subroutine should be placed at the beginning or at the end of program. To define subroutine you use the keyword sub followed by subroutine name and its body. Here is the syntax of subroutine definition.
-
sub subroutine_name{
-
#subroutine body
-
}
For example, here is a simple subroutine to print a message.
-
sub print_message{
-
print "Perl subroutine tutorial";
-
}
To invoke or call subroutine, you use the subroutine name with the prefix is ampersand (&) as follows:
Parameters in subroutine
Parameters are passed to a subroutine as a list which is available in a subroutine as a @_ - an array variable. For example:
-
sub print_list{
-
print "@_\n";
-
}
-
#print: this is Perl subroutine tutorial
-
&print_list("this","is","Perl","subroutine","tutorial");
-
#print: subroutine tutorial
-
&print_list("subroutine","tutorial");
In the line 2, we printed the list variable which was the input parameters of the subroutine. In line 5 and 7, we called subroutine with different list and we got different output.
You can refer to each parameter in a list by using scalar $_[index] for example:
-
sub max{
-
if($_[0] > $_[1]){
-
$_[0];
-
}
-
else{
-
$_[1];
-
}
-
}
-
-
$m = max(10,20);
-
$m2 = max(50,30);
-
print "$m\n";
-
print "$m2\n";
In the above example, we defined a subroutine which is used to return the maximum value of two input parameters. First we compared the first array elements to the second and return the maximum one. We referred to the parameters by using scalar $_[0] and $_[1]. Then we called the subroutine to return the maximum values of two input parameters. Let's go to the next section to see how subroutine returns values.
Returning values
Subroutine returns values which is the last expression evaluated. For example :
-
sub sum{
-
print "sum of two numbers\n";
-
$_[0] + $_[1];
-
}
-
$result = &sum(10,20); # result is 30
-
print $result;
In the sum subroutine above, in the line 3 we added two input parameters and returned the result. If you want to return value immediately from subroutine, you can use return operator, for example:
-
sub min{
-
if($_[0] < $_[1]){
-
return $_[0];
-
}
-
else{
-
return $_[1];
-
}
-
}
-
$m = &min(10,20); # result is 10
-
print $m;
Subroutine returns not only scalar value but also a list of values. See example bellow:
-
sub get_list{
-
return 5..10;
-
}
-
@list = &get_list;
-
print "@list"; #5 6 7 8 9 10