Hack #82. Trace Your Ops

Watch Perl execute individual instructions.

Unlike so-called natively compiled programs, Perl programs are instructions for the Perl virtual machine. When Perl compiles a program, it reduces it to a tree of opcodes, such as "fetch this lexical variable" and "add the attached constant." If you want to see what your program is doing, the best[18] way is to examine each individual opcode.

The B::* modules—the compiler backend to Perl—give you some flexibility in examining compiled code from Perl. They don't give you many opportunities to play with ops as Perl runs them, however. Fortunately, Runops::Trace does.

The Hack

Runops::Trace replaces Perl's standard runloop with an alternate runloop that calls back to Perl code, passing the B::* object representing the next op that will run. This allows you to request and log any data from that op.

Tip

Perl's standard runloop executes the current op, fetches the next op after that, dispatches any signals that have arrived, and repeats.

For example, to count the number of accesses to global symbols within a program, write a callback logger:

package TraceGlobals; use strict; use warnings; use Runops::Trace \\&trace_globals; my %globals; sub trace_globals { return unless $_[0]->isa( 'B::SVOP' ) && $_[0]->name( ) eq 'gv'; my $gv = shift->gv( ); my $data = $globals{ $gv->SAFENAME( ) } ||= { }; my $key = $gv->FILE( ) . ':' . $gv->LINE( ); $data->{$key}++; } END { Runops::Trace->unimport( ); for my $gv ( sort ...

Get Perl Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.