article xmlns:src="http://nwalsh.com/xmlns/litprog/fragment" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" articleinfo titleCalculating Members of the Fibonacci Seriestitle author firstnameNormanfirstname surnameWalshsurname author articleinfo paraThis 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. para sectiontitleRecursive Definitiontitle paraThe 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.para paraThis can be implemented recursively by calculating the preceding two members of the series and returning their sum:para src:fragment id="sub.fib.recursion" ampfib($n-2) + ampfib($n-1); src:fragment section sectiontitleThe functionfibfunction Functiontitle paraThe heart of this program is the recursive function that calculates the members of the Fibonacci series.para paraThe first and second members of the Fibonnacci series are quote1quote; all other values are calculated recursively.para src:fragment id="sub.fib" sub fib { my $n = shift; if ($n lt= 2) { return 1; } else { return src:fragref linkend="sub.fib.recursion" } } src:fragment section sectiontitleCode Preambletitle paraThe program preamble simply establishes a default location for the Perl executable and informs the interpreter that we want to use the strict pragma.para src:fragment id="preamble" #!/usr/bin/perl -w use strict; src:fragment section sectiontitleArgument Checkingtitle paraThis program expects its argument on the command line and it expects that argument to be an unsigned decimal integer.para src:fragment id="argcheck" my $num = shift @ARGV || die; die "Not a number: $num\n" if $num !~ /^\d+$/; src:fragment section sectiontitleThe Programtitle paraThe program prints out the Fibonacci number requested:para src:fragment id="top" src:fragref linkend="preamble" src:fragref linkend="argcheck" print "Fib($num) = ", ampfib($num), "\n"; src:fragref linkend="sub.fib" src:fragment section article