Skip to Content
Perl Hacks
book

Perl Hacks

by Chromatic, Damian Conway, Curtis Ovid Poe, Curtis (Ovid) Poe
May 2006
Beginner
298 pages
6h 51m
English
O'Reilly Media, Inc.
Content preview from Perl Hacks

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 keys %globals ) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl Debugged

Perl Debugged

Peter Scott, Ed Wright
Perl 6 Deep Dive

Perl 6 Deep Dive

Andrew Shitov
Learning Perl 6

Learning Perl 6

brian d foy
Perl by Example

Perl by Example

Ellie Quigley

Publisher Resources

ISBN: 0596526741Supplemental ContentErrata Page