Table of Contents
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.
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); |
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 | } | } |
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; |
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+$/; |
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 |