http://www.perlmonks.org?node_id=686556


in reply to Rewriting sub code on import to add logging

This method isn't exactly recommended. Look carefully at the other methods mentioned above (possibly except the B::Deparse method, which is likely at least as fragile as this).

I ran into a problem like this a while back where I wanted to write a custom function profiler that used DBD::SQLite to store the profile data. It didn't work very well, but it was fun and it's no trouble for me to cut and paste the code in here. (I ripped off ideas from Memoize directly.)

I think this can easily be adapted to what you're trying to do.

use strict; use warnings; for my $package (qw(testpackage)) { my $st_name = "main::" . $package . "::"; my $symbol_table = do { no strict 'refs'; *{$st_name}{HASH}; }; while( my ($k, $v) = each %$symbol_table ) { if( $package->can($k) ) { my $st_fname = $st_name . $k; my $fref = do { no strict 'refs'; *{$st_fname}{CODE}; # from Memoize.pm :: _make_cref() }; next unless $fref and ref $fref eq "CODE"; next if defined prototype $fref; # I'm ignoring prototypes my $newf = sub { my ($r, @r); warn "<beginfunc name=\"$k\">\n"; if( wantarray ) { @r = $fref->(@_); } else { $r = $fref->(@_); } warn "</endfunc>\n"; return $r unless wantarray; @r; }; do { no strict 'refs'; local($^W) = 0; # ``Subroutine $install_name red +efined at ...'' *{$st_fname} = $newf; # also from Memoize.pm :: memoiz +e() } } } } testpackage->f1(); testpackage->f2(); package testpackage; use strict; sub f1 { print "f1!\n"; } sub f2 { print "f2!\n"; }

-Paul