Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Tool to record subroutine calls & return values

by stevieb (Canon)
on Apr 09, 2017 at 18:48 UTC ( [id://1187532]=note: print w/replies, xml ) Need Help??


in reply to Tool to record subroutine calls & return values

Not the most versatile option, but thought I'd throw it out there. I wrote Wrap::Sub quite a while ago as a learning experience that can do this kind of thing. It works by running code before the actual sub is called where you can access the incoming parameters then do work before the actual sub is called, then runs another chunk of code after the real sub is called, where the return value(s) of the sub are received (which again, you can do more work on if desired).

You must list all of the subs you want to wrap (if subs in other packages are desired, specify the full package name of the sub (eg 'Foo::Bar::sub_name').

use warnings; use strict; use Data::Dumper; use Wrap::Sub; my $ws = Wrap::Sub->new( pre => sub { print "\n$Wrap::Sub::name\n"; print "args:\n"; print Dumper \@_; }, post => sub { print "return:\n"; print Dumper $_[1][0]; } ); my @wrapped; for (qw(foo bar)){ push @wrapped, $ws->wrap($_); } foo(a => 1, b => 2); bar(10); sub foo { my %hash = @_; return [1, 2, 3]; } sub bar { my $x = shift; return $x ** 2; }

Output:

main::foo args: $VAR1 = [ 'a', 1, 'b', 2 ]; return: $VAR1 = [ 1, 2, 3 ]; main::bar args: $VAR1 = [ 10 ]; return: $VAR1 = 100;

Of course, the formatting of the output isn't very creative, but that's simple to fix to your liking within the pre and post subs (which are simple code references, so you can define them anywhere, not necessarily within the init call). Note that you can also wrap all subs within a module in one pass as well: my $module_subs = $ws->wrap('My::Module');, so you can selectively wrap entire modules in a loop as opposed to individual subs like I did in the above example.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1187532]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-19 04:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found