(Brett Trost) writes:
> OK, I wanted to make a recursive fibonacci method in Perl, and I can't
> understand why it is not working, especially since I wrote the exact
> same thing in Java and it works. Here's the perl code:
>
> #!/usr/bin/perl
> sub fib {
> $num = shift;
> return 0 if $num == 1;
> return 1 if $num == 2;
> return fib($num - 1) + fib($num - 2);
> }
>
> print fib($ARGV[0]);
>
<snip>
> The perl one keeps on running forever. If I print out $num, it goes
> rapidly into the negatives. Why is this, when the base case should
> take care of that, and the Java code has the exact same logic and
> works?! It must be an error with my Perl, but I can't find it.
> Thanks for any help.
I put in
#! /usr/bin/perl -w
at the start and debugged ....
../test.pl 8
Deep recursion on subroutine "main::fib" at ./test.pl line 7.
Adding :
#! /usr/bin/perl -w
use strict;
and using
my $num = shift;
gives the right results.
hth
Lesley
---
email address munged : remove relevant y if nec.