4.1. Function Recursion

Functions can call other functions. In fact, a function can call itself, either directly or indirectly. When a function calls itself it is known as recursion, a Computer Science methodology which can be implemented with or without functions.

Here's an example where recursion is used to find all the permutations of splitting 10 among three numbers:

use strict;
use warnings;

sub mysplit
{
    my ($total, $num_elems, @accum) = @_;

    if ($num_elems == 1)
    {
        push @accum, $total;
        print join(",", @accum), "\n";

        return;
    }

    for (my $item=0 ; $item <= $total ; $item++)
    {
        my @new_accum = (@accum, $item);
        mysplit($total-$item, $num_elems-1, @new_accum);
    }
}

mysplit(10,3);

A couple of notes are in place. First of all, perl does not handle tail recursion very well, at least not in the current incarnation of the compiler. If your recursion can be done using a simple loop, do it with it.

Secondly, some systems (such as Microsoft Windows) limit an executable to a certain amount of stack, as far as such languages as Assembler or C are concerned. This should not be of any concern to perl hackers, because the perl interpreter does not translate a perl function call into a C function call. (not to mention that the perl interpreter on those systems is compiled with enough stack for itself).

Sometimes, recursion is helpful, but if you see that your recursion is getting too deep, you should consider using your own dedicated stack (which can be implemented as an array) instead. It's a good programming practice.


Written by Shlomi Fish