Calculating Members of the Fibonacci Series Norman Walsh 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.
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: &fib($n-2) + &fib($n-1);
The <function>fib</function> 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. sub fib { my $n = shift; if ($n <= 2) { return 1; } else { return } }
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. #!/usr/bin/perl -w use strict;
Argument Checking This program expects its argument on the command line and it expects that argument to be an unsigned decimal integer. my $num = shift @ARGV || die; die "Not a number: $num\n" if $num !~ /^\d+$/;
The Program The program prints out the Fibonacci number requested: print "Fib($num) = ", &fib($num), "\n";