dgaramond2 has asked for the wisdom of the Perl Monks concerning the following question:

Trapping (or "transparent wrapping") of function/method calls can be used, among others, to add a layer of authentication or for logging/debugging or even perhaps some interesting programming techniques. Ruby has alias_method which can be used for this purpose. Does Perl have something equivalent or to the same effect? The AUTOLOAD mechanism works only for calling non-existing subs (equivalent to Ruby's method_missing).

Replies are listed 'Best First'.
Re: Trapping calls to existing Perl subs?
by duff (Parson) on May 31, 2007 at 03:59 UTC
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Trapping calls to existing Perl subs?
by Util (Priest) on May 31, 2007 at 04:08 UTC

    Perl 6 has a new .wrap method just for this sort of thing.

    In Perl 5, this technique comes to my (sleepy) mind:

    use strict; use warnings; sub greet { my ($name) = @_; print "Hi, $name!\n" or return 'Shame :('; return 'Glory !'; } sub wrap_the_sub { my ($sub_name) = @_; my $sub_ref = \&{$sub_name}; my $wrapping_sub = sub { my @args = @_; print "Entering '$sub_name'\n"; my $rc = $sub_ref->(@args); print "Exiting '$sub_name'\n"; # Really need some wantarray() trick there... return $rc; }; no strict 'refs'; no warnings 'redefine'; *{$sub_name} = $wrapping_sub; } wrap_the_sub('greet'); my $result = greet('Util'); print "Result was: '$result'\n";
    Output:
    Entering 'greet' Hi, Util! Exiting 'greet' Result was: 'Glory !'

Re: Trapping calls to existing Perl subs?
by friedo (Prior) on May 31, 2007 at 04:31 UTC
Re: Trapping calls to existing Perl subs?
by educated_foo (Vicar) on May 31, 2007 at 08:13 UTC
    Sure! Better still, unlike most ruby solutions to this problem, this actually nests:
    sub wrap { my ($name, $outer) = @_; my $inner = \&$name; *{$name} = sub { $outer->($inner, @_); }; } sub foo { print "foo\n"; } wrap 'foo', sub { my $foo = shift; print "called foo with (@_)\n"; $foo->(@_); }; foo('args'); wrap 'foo', sub { my $foo = shift; print "called AGAIN foo with (@_)\n"; $foo->(@_); }; foo('more args'); __END__ called foo with (args) foo called AGAIN foo with (more args) called foo with (more args) foo
Re: Trapping calls to existing Perl subs?
by salva (Canon) on May 31, 2007 at 07:40 UTC
    you can also use the debugger hooks to do that, read perldebguts.