BluePerl has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perlmonks, I try to call a derived class from a base class. See code:
package person; use Method::Signatures; method new (%args) { return bless {%args}, $self; } method name () { return "*person*\n"; } method myname () { return name() } package eva; our @ISA = ("person"); use Method::Signatures; method name () { return "eva\n"; } my $p = new person (); print $p->name (); my $e = new eva (); print $e->name(); print $e->myname(); # returns: # *person* # eva # *person* 1;

How can I achieve, that $e->myname () returns "eva". Which means, that a direved class calls its baseclass (function myname) and the baseclass should call the name function of the Child class.

Replies are listed 'Best First'.
Re: OO-Perl Question: How to call a derived class from a base class?
by poj (Abbot) on Jul 24, 2015 at 12:21 UTC
    method myname () { return $self->name(); }
    poj
      Thanks a lot, this was what I looked for!
        Quick explanation of why that works:
        • In Perl, an object is a reference which has been tied to a particular package (class) by blessing it.
        • When you call $object->foo, it executes sub foo from the package that $object has been blessed into - package eva if it's an eva object or package person if it's a base person object.
        • When you call just plain foo, it executes sub foo from the package in which the calling code was defined. Since myname is defined in package person (and not overridden), it will always call person::name regardless of the object's class.
        • If your methods used parameters or $self, you would have also noticed another difference: $object->foo implicitly passed $object as its first parameter (so it can be used to populate $self), but just plain foo does not. This can, obviously, cause issues if your methods use $self or parameters, so you should always call them as either $object->foo if you want them to be polymorphic or class->foo if you want to lock them to a specific class's implementation.