Return Values

A subroutine is always part of some expression. The value of the subroutine invocation is called the return value. The return value of a subroutine is the value of the return statement or of the last expression evaluated in the subroutine.

For example, let’s define this subroutine:

sub sum_of_a_and_b {
	return $a + $b;
}

The last expression evaluated in the body of this subroutine (in fact, the only expression evaluated) is the sum of $a and $b, so the sum of $a and $b will be the return value. Here’s that in action:

$a = 3; $b = 4;
$c = sum_of_a_and_b();   # $c gets 7
$d = 3*sum_of_a_and_b(); # $d gets 21

A subroutine can also return a list of values when evaluated in a list context. Consider this subroutine and invocation:

sub list_of_a_and_b {
return	 ($a,$b);
}
$a = 5; $b = 6;
@c = list_of_a_and_b(); # @c gets (5,6)

The last expression evaluated really means the last expression evaluated, rather than the last expression defined in the body of the subroutine. For example, this subroutine returns $a if $a > 0; otherwise, it returns $b:

sub gimme_a_or_b {
		if ($a > 0) {
			print "choosing a ($a)\n";
	return		$a;
		} else {
			print "choosing b ($b)\n";
	return		$b;
		}
}

These examples are all rather trivial. It gets better when we can pass values that are different for each invocation into a subroutine, instead of having to rely on global variables. In fact, this discussion is coming right up.

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.