Better Living Through Thinking

Subroutine Tracing

Thu, 05 Oct 2006

Sometimes we want to see the call chain of a subroutine, just to see where our data has been. For example, a program:

blech();
exit;

might have this kind of chain:

blech() -> baz() -> bar() -> foo()

Thus:

sub blech { baz() }
sub baz   { bar() }
sub bar   { foo() }
sub foo   { print "I'm in foo!" }

We add a little subroutine to help us trace this call chain:

sub call_trace {  
    my ($pack, $sub);
    my $i = 1;
    do { ($pack, $sub) = (caller($i++))[0,3];
         warn ' ' x $i . $sub . "\n" if $sub;
    } while defined $sub;
}

And modify our final subroutine:

sub foo   { print "I'm in foo!"; call_trace() }

Now we get a nice bit of output:

I'm in foo!
  main::foo
   main::bar
    main::baz
     main::blech
[ category: /perl | link: subroutine_tracing ]

Audio Broadcast

(standby)

Moon Status

Phase: 99.97%
Illuminated: 0.00%
Age (days): 29.52
moon phase 0.999727040164869 Sun May 20 17:36:09 MDT 2012