Calculating Members of the Fibonacci Series

Norman Walsh


Table of Contents

1. Recursive Definition
2. The fib Function
3. Code Preamble
4. Argument Checking
5. The Program

This trivial document describes a simple, recursive implementation of the Fibonacci series in Perl. The principal motivation for this document is to demonstrate the use of Literate XML.

1. Recursive Definition

The Fibonacci series begins: 1 1 2 3 5 8 13... Each member of the series, after the first two, is the sum of the preceding two members.

This can be implemented recursively by calculating the preceding two members of the series and returning their sum:

§1.1: §2.1

  1| &fib($n-2) + &fib($n-1);

2. The fib Function

The heart of this program is the recursive function that calculates the members of the Fibonacci series.

The first and second members of the Fibonnacci series are “1”; all other values are calculated recursively.

§2.1: §5.1

  1| sub fib {
   |     my $n = shift;
   | 
   |     if ($n <= 2) {
  5|         return 1;
   |     } else {
   |         return §1.1. Recursive Definition
   |     }
   | }

3. Code Preamble

The program preamble simply establishes a default location for the Perl executable and informs the interpreter that we want to use the strict pragma.

§3.1: §5.1

  1| #!/usr/bin/perl -w
  2| 
  3| use strict;

4. Argument Checking

This program expects its argument on the command line and it expects that argument to be an unsigned decimal integer.

§4.1: §5.1

  1| my $num = shift @ARGV || die;
  2| 
  3| die "Not a number: $num\n" if $num !~ /^\d+$/;

5. The Program

The program prints out the Fibonacci number requested:

§5.1

  1| §3.1. Code Preamble
   | §4.1. Argument Checking
   | 
   | print "Fib($num) = ", &fib($num), "\n";
  5| 
   | §2.1. The fib Function