Mark Dominus on 27 May 2006 21:00:36 -0000


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Little debugging thingy for recursive functions


The program I'm working on right now has a method ->expand that calls
a method ->for_terms that calls ->_expand_term that might make a
recursive call to itself by calling ->for_terms again.

The attached function has been useful in testing and debugging it.
If function "foo" says

        debug "message"

it emits a message like:

        * * * * message

indented according to how deeply-nested the calls to "foo" are at the
time the call was made.  For example:

        sub fib {
          my $n = shift;
          return $n if $n < 2;
          debug "fib($n):\n";
          my $res = fib($n-1) + fib($n-2);
          debug "result: $res\n";
          $res;
        }

emits an output like:

        * fib(5):
        * * fib(4):
        * * * fib(3):
        * * * * fib(2):
        * * * * result: 1
        * * * result: 2
        * * * fib(2):
        * * * result: 1
        * * result: 3
        * * fib(3):
        * * * fib(2):
        * * * result: 1
        * * result: 2
        * result: 5


Here's the debug() function:

        sub debug {
          my $depth = 1;
          my $cdepth = 0;
          my $sub = (caller($depth))[3];
          my @c;
          $depth++, $cdepth += ($c[3] eq $sub) while @c = caller($depth);
          my $i = "* " x $cdepth;
          print $i, @_;
        }

-
**Majordomo list services provided by PANIX <URL:http://www.panix.com>**
**To Unsubscribe, send "unsubscribe phl" to majordomo@lists.pm.org**