in reply to How to redefine a modules private function?
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:
package MyBase; use strict; use warnings; use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(bar); sub FOO() {42} sub bar { return FOO(); } 1;
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:
package MySub; use strict; use warnings; sub _filter { my $module = $_[1]; if ($module =~ m/^MyBase/) { foreach my $dir (@INC[1..$#INC]) { if (-e "$dir/MyBase.pm" && -f _) { open FH, '<', "$Bin/lib/MyBase.pm" or die $!; last; } } die "Couldn't find MyBase.pm in @INC\n" unless defined *FH; return \'', \*FH, sub { if (length $_) { $_ =~ s/(sub FOO\(\)\s*\{)(\d+)(\})/${1}44${3}/; return 1; } else { return 0; } }; } return (); } BEGIN {unshift @INC, \&_filter} use MyBase; use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(baz); sub baz { return bar(); } 1;
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:
#!/usr/bin/env perl use strict; use warnings; use FindBin qw($Bin); use lib "$Bin/lib"; use MySub; print baz(), "\n";
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to redefine a modules private function?
by LanX (Saint) on Mar 09, 2022 at 16:40 UTC | |
by davido (Cardinal) on Mar 09, 2022 at 16:47 UTC | |
|
Re^2: How to redefine a modules private function?
by perlfan (Parson) on Mar 10, 2022 at 06:44 UTC | |
by haukex (Archbishop) on Mar 10, 2022 at 06:54 UTC |