www.perl.com
Perl Programming
Subroutines - Example
  • A more typical example
    • Declare subroutine
    • Copy arguments
    • Check arguments
    • Perform computation
    • Return results

        sub fibonacci {
            my ($n) = @_;
            die "Number must be positive" if $n <= 0;
            return 1 if $n <= 2;
            return (fibonacci($n-1) + fibonacci($n-2));
        }

        foreach my $i (1..5) {
            my $fib = fibonacci($i);
            print "fibonacci($i) is $fib\n";
        }
      

        fibonacci(1) is 1
        fibonacci(2) is 1
        fibonacci(3) is 2
        fibonacci(4) is 3
        fibonacci(5) is 5
      
Previous http://stuff.mit.edu/iap/perl/