Just another Perl shrine | |
PerlMonks |
Re: How to redefine a modules private function?by davido (Cardinal) |
on Mar 09, 2022 at 16:17 UTC ( [id://11141951]=note: print w/replies, xml ) | Need Help?? |
Not ready for production. :) With Perl, we can insert code into @INC so that we get ahead of the constant definition: First, MyBase.pm. This module defines a constant, FOO of 42. But we live in a universe where FOO needs to be 44. Here's the example base:
If someone were to use this module and call bar(), its return value would be 42. Now I need a module that depends on MyBase.pm. We'll call it MySub.pm. Here's where I can get in front of loading MyBase. To do that I'll insert code into @INC so that use and require get a little modified behavior:
Here I have a subroutine named baz which calls MyBase::bar(), which returns the constant stored in MyBase::FOO, which would normally be 42. However, I've inserted a subroutine into @INC named _filter() that looks for the loading of MyBase.pm and replaces the FOO definition with a new one, with a value of 44. Finally, a small sample app using this:
If we didn't override FOO in MyBase, this code would print 42. But the approach is successful, and the output is now 44. Obviously this isn't necessarily robust. A better approach would be to submit a patch to the maintainers of AnyEvent::DNS that makes the hard-coded value configurable. Just by removing the prototype it would become possible to subclass and override, or monkeypatch, for example. But in a pinch, a lot of things are possible. Look at the documentation in require for an explanation of how my approach works. Dave
In Section
Seekers of Perl Wisdom
|
|