O'Reilly logo

Perl Hacks by Curtis Poe, Curtis Ovid Poe, Damian Conway, Chromatic

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hack #74. Trace All Used Modules

See what modules your program uses—and what modules those modules use!

Perhaps the most useful feature of Perl 5 is module support, allowing the use of existing, pre-written code. With thousands of modules on the CPAN available for free, it's likely that any code you write will use at least a few other pieces of code.

Of course, all of the modules you use optionally use a few modules of their own, and so on. You could find yourself loading dozens of pieces of code for what looks like a simple program. Alternately, you may just be curious to see the relationships within your code.

Wouldn't it be nice to see which modules your code loaded from where? Now you can.

The Hack

The easiest way to gather the information on what Perl modules any piece of code loads is a little-known feature of @INC, the magic variable that governs where Perl looks to load modules. If @INC contains a code reference, it will execute that reference when attempting to load a module. This is a great place to store code to manage library paths, as PAR and The::Net (http://www.perlmonks.org/?node_id=92473, not on the CPAN) do. It also works well to collect interesting statistics:

package Devel::TraceUse; use Time::HiRes qw( gettimeofday tv_interval ); BEGIN { unshift @INC, \\&trace_use unless grep { "$_" eq \\&trace_use . '' } @INC; } sub trace_use { my ($code, $module) = @_; (my $mod_name = $module) =~ s{/}{::}g; $mod_name =~ s/\\.pm$//; my ($package, $filename, $line) = caller( ); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required