Better Living Through Thinking

Lightweight Tracing of a Perl Program

Thu, 05 Oct 2006

Perl filters are truly a marvel. The following simple filter allows you to trace your programs without changing the program to be traced other than adding:

use Tracer;

to the top of the module or program to be traced. If you don't mind wholesale tracing, you can just run your program *completely unmodified* like this:

perl -MTracer program.pl

Here's the magic:

package Tracer;

use Filter::Util::Call;

sub import {
    my($type, @args) = @_;
    filter_add([]);
}

sub filter {
    my $self = shift;
    my $status;
    return $status unless $status = filter_read();
    s/^(sub .+\{)/$1\nprint STDERR "TRACE: Now entering " . (caller(0))[3] . "\n";/;
    $status;
}

1;

Each subroutine that Perl enters will print out a line:

TRACE: Now entering main:blech
[ category: /perl | link: lightweight_tracing ]

Audio Broadcast

(standby)

Moon Status

Phase: 99.97%
Illuminated: 0.00%
Age (days): 29.52
moon phase 0.99971860303475 Sun May 20 17:35:45 MDT 2012