Return Values of a Function using Perl
by Geethalakshmi[ Edit ] 2010-09-17 14:17:20
Return Values of a Function using Perl
A subroutine always returns an expression. This is controlled by a 'return' statement or the last expression evaluated. Note: The last expression evaluated literally means the last expression evaluated, and not just the last expression within the subroutine.
sub sum_a_b {
return $a + $b
}
$a = 3;
$b = 4;
$c = sum_a_b(); # $c = 7
$d = 3 * sum_a_b(); # $d = 21
You can return a list of values by enclosing the return value in '( )'s.
sub list_a_b {
return($a, $b);
}
$a = 5;
$b = 6;
@c = list_a_b(); # @c = 5, 6
The following demostrates the last expression logic. The following returns $a if $a >0, otherwise it returns $b.
sub get_a_b {
if ($a >0 ) {
print "chosing a ($a) \n";
return $a;
} else {
print "chosing b ($b) \n";
return $b;
}
}