Reputation: 21
I'm new to Perl and have been directed to Moose as the go to source for Perl OO but I am having some problems with making it work. Specifically, methods of the superclass do not seem to be inherited. To test this I have created three files which contain the following:
thingtest.pl
use strict;
use warnings;
require "thing_inherited.pm";
thing_inherited->hello();
thing.pm
package thing;
use strict;
use warnings;
use Moose;
sub hello
{
print "poo";
}
sub bye
{
print "naaaa";
}
1;
And finally, thing_inherited.pm
package thing_inherited;
use strict;
use warnings;
use Moose;
extends "thing";
sub hello
{
bye();
}
1;
So what one would normally expect is for method bye to be inherited as part of the subclass but I am given this error instead...
Undefined subroutine &thing_inherited::bye called at thing_inherited.pm line 11.
Can anyone explain if I'm doing something wrong here? Thanks!
edit: In doing this I have come across another conundrum: calling a method in my base class from my superclass that has should have been overwritten by the superclass is not overwritten. Say I had
sub whatever
{
print "ignored";
}
in my base class and added
whatever();
in my bye method, calling bye would not produce the overwritten result, only print "ignored".
Upvotes: 2
Views: 747
Reputation: 36
Just a few fixes. thing.pm was fine, but see the changes to thingtest.pl and thing_inherited.pm.
thingtest.pl: need to instantiate the object before using it, then you can use the method
use thing_inherited;
use strict;
use warnings;
my $thing = thing_inherited->new();
$thing->hello();
thing_inherited.pm: since the hello method is calling a method in it's class, you need to tell it just that
package thing_inherited;
use strict;
use warnings;
use Moose;
extends "thing";
sub hello {
my $self = shift;
$self->bye();
}
1;
Output:
$ perl thingtest.pl
naaaa$
Upvotes: 0
Reputation: 385897
You have a function call, not a method call. Inheritance only applies to classes and objects, i.e. method calls. A method call looks like $object->method
or $class->method
.
sub hello
{
my ($self) = @_;
$self->bye();
}
By the way, require "thing_inherited.pm";
should be use thing_inherited;
Upvotes: 7