Chapter 5. Fruitful Subroutines

Most of the Perl functions we have used, such as the math functions, produce return values. But most of the subroutines we’ve written so far are void: they have an effect, like printing a value, but they don’t have a return value. In this chapter you will learn to write fruitful functions.

Return Values

Calling a fruitful function generates a return value, which we usually assign to a variable or use as part of an expression:

my $pi = 4 * atan 1;
my $height = $radius * sin $radians;

Many of the subroutines we have written so far are void. Speaking casually, they have no usable return value; more precisely, their return value may be Any, (), or True.

In this chapter, we are (finally) going to write fruitful subroutines. The first example is area, which returns the area of a circle with the given radius:

sub area($radius) {
    my $circular_area = pi * $radius**2;
    return $circular_area;
}

We have seen the return statement before, but in a fruitful function the return statement includes an expression. This statement means: “Return immediately from this function and use the following expression as a return value.” The expression can be arbitrarily complicated, so we could have written this function more concisely:

sub area($radius) {
    return pi * $radius**2;
}

On the other hand, temporary variables like $circular_area can make debugging easier. They may also help document what is going on.

Sometimes it is useful to have multiple return statements, for example ...

Get Think Perl 6 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.