Recursion in Perl

Our example demonstrates recursive functions in Perl. Here’s a classic example.

use strict;
use warnings;

# This fact function calls itself until it reaches the
# base case of fact(0).
sub fact {
    my $n = shift;
    if ($n == 0) {
        return 1;
    }
    return $n * fact($n - 1);
}

print fact(7) . "\n";

# In Perl, closures can also be recursive. We don't need to
# declare the function separately as we did in the original example.
my $fib;
$fib = sub {
    my $n = shift;
    if ($n < 2) {
        return $n;
    }
    return $fib->($n - 1) + $fib->($n - 2);
};

print $fib->(7) . "\n";

This fact function calls itself until it reaches the base case of fact(0).

In Perl, closures can also be recursive. We don’t need to declare the function separately as we did in the original example. The $fib function is defined as an anonymous subroutine and assigned to a scalar variable.

Since $fib was previously declared, Perl knows which function to call with $fib here.

To run the program, save it as recursion.pl and use the perl command:

$ perl recursion.pl
5040
13

In this Perl version, we’ve maintained the structure and explanation of the original example while adapting it to Perl’s syntax and conventions. The recursive factorial and Fibonacci functions work in a similar manner to the original, demonstrating how recursion can be implemented in Perl.