chris chris - 18 days ago 4x
Perl Question

Perl: enforce inheritance of modules

I have a Perl package (e.g. car) that is meant to be a base class of some other modules (e.g. van, limousine, convertible, ...) -

use base ("car");

in the pm-file of van, ...

I need to make sure car is not used - only the use of the inherited objects (van, limo, ...) is allowed.

Today I do it if ref () inside the base-class. If it returns the name of "car" I know it is used without inheritance and then I quit with an error.

If van, ... is used ref () would return "van", ...

Is there a more elegant/static way to do that. Lets say a way I can get a sort of syntax-error??

And no: I do not like to discuss the weakness of Perl in OO-topics compared to OO-languages ;-)

Here is a sample. It works.

The question is if the is a more better way to do the check in car::new.
package car;

sub new
my $class = shift;
my $self = {};
bless ($self, $class);

if(ref($self) eq "car") # thats my check to make sure beep exists
{ die "no allowed because no beep here";

$return $self;

sub honk
{ beep (); # only defined in the inherited class (van, ...)

package van;

use car;
use base ("car");

sub beep
print "tuuuut";
car->new ()->honk (); # dies
# if no ref-check it would crush because no beep in car.

van->new ()->honk (); # ok but maybe not most elegant


You don't show your code, but it sounds like you aren't checking in the right place; you should only need to do this in the constructor:

sub new {
    my ($class, @other_args) = @_;
    if ($class eq __PACKAGE__) {
        Carp::croak "must be subclassed";

But no, there isn't a way to do it at compile time.