in reply to Hijacking a method

I can highly recommend Hook::LexWrap. It does precisely what you are asking for.
package Obj; sub new { my $class = shift; my $id = shift; return bless { id => $id }, $class; } sub method1 { my $self = shift; print "Object $self->{'id'}: Method 1\n"; } sub method2 { my $self = shift; print "Object $self->{'id'}: Method 2\n"; } package main; use Hook::LexWrap; wrap 'Obj::method1', pre => sub { print "PRE method1\n" }, post => sub + { print "POST method1\n\n" }; wrap 'Obj::method2', pre => sub { print "PRE method2\n" }, post => sub + { print "POST method2\n\n" }; my $object1 = new Obj(1); my $object2 = new Obj(2); $object1->method1; $object1->method2; $object2->method1; $object2->method2; ## OUTPUT PRE method1 Object 1: Method 1 POST method1 PRE method2 Object 1: Method 2 POST method2 PRE method1 Object 2: Method 1 POST method1 PRE method2 Object 2: Method 2 POST method2

Replies are listed 'Best First'.
Re^2: Hijacking a method
by Transient (Hermit) on Jun 17, 2009 at 17:14 UTC
    Fantastic! That's exactly what I'm looking for! Thanks lostjimmy =)

    FWIW I did actually get this code to work, but I'm not sure how safe/portable/full of holes it is:
    *Obj::myFunkyLogHandler = \$myFunkyLogHandler; *Obj::doSomething2 = \&Obj::doSomething; *Obj::doSomething = sub { $myFunkyLogHandler->Log("Hello there!"); my $ret_val = Obj::doSomething2( @_ ); $myFunkyLogHandler->Log("Bye for now!"); return $ret_val; };
    so I guess I was a little closer to what I wanted than I thought!
      I would guess this method is the most portable since you don't need to install anything from CPAN to get it to work and this works on most (if not all) perls. The sub-class and/or cpan methods are certainly cleaner and more readable, but this is definitely portable.

      -Paul

      Like jettero says, your version is very portable, and should be safe for what you are using it for. It is essentially what LexWrap does, minus some additional features and error checking.

      On the other hand, LexWrap is a pure perl module, so there's really no issue with just including it with your script if you're looking for a clean wrapping module to use.