Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

What is the correct way to override a Package Method

by unlinker (Monk)
on Oct 02, 2007 at 15:50 UTC ( #642148=perlquestion: print w/replies, xml ) Need Help??
unlinker has asked for the wisdom of the Perl Monks concerning the following question:

O Wise and Kind Monks, may the light of your wisdom shine on me. I recently saw code that over-rode a method in a package by its own version using typeglobs. If sub-classing is not an option, what is the correct, safe and canonical way to do this? Gratitude
  • Comment on What is the correct way to override a Package Method

Replies are listed 'Best First'.
Re: What is the correct way to override a Package Method
by kyle (Abbot) on Oct 02, 2007 at 16:08 UTC

    I think typeglobs are the way to go if you want to figure out at run time what method to override.

    my $package_method = 'Foo::Bar::baz'; my $orig = \&($package_method}; no warnings; *{$package_method} = sub { pre(); $orig->(@_); post() };

    You can also do this:

    package Foo::Bar; sub baz { print "I am the original!\n" } package main; sub Foo::Bar::baz { print "I am the new baz!\n" } Foo::Bar::baz();

    Or you can toss in your own definition between a couple package lines anywhere you want. You can also build up a string like the above at run time and wrap it in an eval whenever you're ready.

    Note that these various methods can have subtle differences when it comes to caller, and maybe some other stuff.

Re: What is the correct way to override a Package Method
by tinita (Parson) on Oct 02, 2007 at 20:39 UTC
    you can also use Sub::Install which hides all the dirty details about globs and strict from you.
      Thank you. This seems to be the best way to do it. may I trouble you for a small illustrative example? Here is what I want to do. I have a Package written by someone else and I want to override one of the methods in that Package without touching its source. However I want to do it in a way that even if that package calls, I want it to use my version. Thank you once again
        uhm, isn't the documentation Sub::Install clear enough?
        to give you an example i would just copy&paste from there anyway...

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://642148]
Approved by kyle
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (6)
As of 2018-04-23 14:00 GMT
Find Nodes?
    Voting Booth?