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

I need to redefine a method in a package and then be able to call the original method. I understand that subclassing would be better so I could use SUPER, but I am dealing with constraints being imposed on me. So how do I store a reference to the original method so that I can use it? Some sort of typeglob?
  • Comment on How to redefine a method and still reference the original.

Replies are listed 'Best First'.
Re: How to redefine a method and still reference the original.
by dragonchild (Archbishop) on Feb 17, 2005 at 18:35 UTC
    my $old = \&method; *method = sub { # Do something new my @return = $old->( @args ); # Do something else };

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

      You might want to add a pair of braces and a no warnings 'redefine'; to that.

      my $old = \&method; { no warnings 'redefine'; *method = sub { # Do something new my @return = $old->( @args ); # Do something else }; }

      Examine what is said, not who speaks.
      Silence betokens consent.
      Love the truth but pardon error.
Re: How to redefine a method and still reference the original.
by gaal (Parson) on Feb 17, 2005 at 18:54 UTC
    ++dragonchild gave the precise answer to your question.

    If the application you're thinking of is transparently wrapping existing code (i.e., have the method being redefined be called by that which redefines it), look at Hook::LexWrap. You may find Aspect interesting also.

Re: How to redefine a method and still reference the original.
by RazorbladeBidet (Friar) on Feb 17, 2005 at 18:36 UTC
    Can you provide a little more information:

    how do these methods differ (# of args, return value)?
    Are they being called from the same place?
    Is one called only in a certain area and never called again - or do they both need to exist for the lifetime of the package?



    Disregard - listen to dragonchild :)
    --------------
    It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs