I’m not thinking too clearly right now and possibly overlooking something simple. I’ve been thinking about this for a while and been searching, but can’t really think of any sensible search queries anymore that would lead me to what i seek.
In short, I’m wondering how to do module inheritance, in the way base.pm/parent.pm do it for object-oriented modules; only for Exporter-based modules.
A hypothetical example of what i mean:
Here’s our script. It originally loaded Foo.pm and called baz() from it, but baz() has a terrible bug (as we’ll soon see), so we’re using Local/Patched/Foo.pm now which should fix the bug. We’re doing this, because in this hypothetical case we cannot change Foo (it is a cpan module under active development, you see), and it is huge (seriously).
#!/usr/bin/perl
# use Foo qw( baz [... 100 more functions here ...] );
use Local::Patched::Foo qw( baz [... 100 more functions here ...] );
baz();
Here’s Foo.pm. As you can see, it exports baz(), which calls qux, which has a terrible bug, causing things to crash. We want to keep baz and the rest of Foo.pm though, without doing a ton of copy-paste, especially since they might change later on, due to Foo still being in development.
package Foo;
use parent 'Exporter';
our @EXPORT = qw( baz [... 100 more functions here ...] );
sub baz { qux(); }
sub qux { print 1/0; } # !!!!!!!!!!!!!
[... 100 more functions here ...]
1;
Lastly, since Foo.pm is used in MANY places, we do not want to use Sub::Exporter, as that would mean copy-pasting a bandaid fix to all those many places. Instead we’re trying to create a new module that acts and looks like Foo.pm, and indeed loads 99% of its functionality still from Foo.pm and just replaces the ugly qux sub with a better one.
What follows is what such a thing would look like if Foo.pm was object-oriented:
package Local::Patched::Foo;
use parent 'Foo';
sub qux { print 2; }
1;
Now this obviously will not work in our current case, since parent.pm just doesn’t do this kinda thing.
Is there a clean and simple method to write Local/Patched/Foo.pm (using any applicable CPAN modules) in a way that would work, short of copying Foo.pm’s function namespace manually?
Just adding in yet another way to monkey-patch
Foo‘squxfunction, this one without any manual typeglob manipulation.This works because Perl’s packages are always mutable, and so long as the above code appears after loading
Foo.pm, it will override the existingbazroutine. You might also needno warnings 'redefine';to silence any warnings.Then to use it:
You could do away with the two
uselines by writing a custom import method inLocal::Patched::Fooas follows:And then it is just: