AFAIK inheritance in Perl is usually set up like this:
package Mule;
our @ISA = ("Horse", "Donkey");
Are there any examples where use base
(or use parent
) is better instead?
use base qw(Horse Donkey);
This is roughly equivalent to:
BEGIN {
require Horse;
require Donkey;
push @ISA, qw(Horse Donkey);
}
It is tidier if you need to load the modules code as well as inheriting from them. BTW, there are issues with multiple inheritance, but thats a different question :)
Edit: Compile-time v. run-time advantages:
If you want to decide to use a given module at run-time, then you can test and add the module to your parents:
if (eval { require X }) { push @ISA, 'X'; }
Establishing inheritance at compile time avoids a particularly hard to debug dependency loop, illustrated below.
# Child.pm
package Child;
our @ISA = qw(Mother);
use Foo;
# Mother.pm
package Mother;
sub wibble { 42 }
# Foo.pm
package Foo;
use Child;
Child->wibble;
If you "use Child" before "use Foo" then Foo will try to call Child->wibble
before its established its inheritance on Mother
. If instead Child were to use parent qw(Mother)
its inheritance would be established before it tried to load anything else.
I've been this sort of dependency loop in private, corporate code that tends to be a bit more intertwined than public code. It sucks to debug, which is why I'd recommend always establishing inheritance at compile-time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With