Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

monkey patching an entire module

by perl5ever (Pilgrim)
on Apr 21, 2009 at 15:01 UTC ( [id://759011]=perlquestion: print w/replies, xml ) Need Help??

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

Using local() it's easy to monkey patch a variable, and here is a way of monkey patching a method of a particular instance.

Suppose you want to monkey patch an entire module? What's the best way to go about it?

There will be two cases: one where the module has not been loaded yet and the case where it has been. And, to be most useful, you'd want the patching to be reversible.

Replies are listed 'Best First'.
Re: monkey patching an entire module
by ikegami (Patriarch) on Apr 21, 2009 at 15:29 UTC
Re: monkey patching an entire module
by ikegami (Patriarch) on Apr 21, 2009 at 15:27 UTC

    A simple trick that should work for the common usage: Make a sub named "My::Module" that returns either the string "Monkeypatch::My::Module" or "My::Module".

    You'll have to declare the sub before the first instance of "My::Module" is compiled.

    Ah dang, it won't work if someone inherits from the class. Ah well, I'll post it anyway in case it helps.

Re: monkey patching an entire module
by krishnoid (Novice) on Apr 22, 2009 at 01:17 UTC
    The last couple YAPCs had Ricardo Signes discuss Sub::Exporter , which is capable of doing all kinds of weird stuff with modules and methods. There's a tutorial for it too.
Re: monkey patching an entire module
by pileofrogs (Priest) on Apr 22, 2009 at 14:32 UTC

    What's a "monkey patch"?

      Seemingly, it's defined as Monkey Patching

      Update:

      Doh !! Link updated (forgot to remove the http://...wiki bit from the front) - thanx to Argel

      A user level that continues to overstate my experience :-))
Re: monkey patching an entire module
by pileofrogs (Priest) on Apr 22, 2009 at 15:57 UTC
Re: monkey patching an entire module
by Anonymous Monk on Apr 21, 2009 at 15:28 UTC
    Don't!
      You forgot to show your working out.

      --
      use JAPH;
      print JAPH::asString();

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://759011]
Front-paged by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-04-20 02:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found