cajwine cajwine - 7 months ago 19
Perl Question

Using "override" or just plain redefine the subroutine in perl

Have this example code - 2 packages which extends the

Some
package and redefines the
func
method.

use 5.014;
use warnings;

package Some {
use Moose;
use warnings;
sub func { say 'func from Some'; }
}

package Over {
use Moose;
use warnings;
extends 'Some';
override 'func' => sub { say 'func from Over'; };
}

package Plain {
use Moose;
use warnings;
extends 'Some';
sub func { say 'func from Plain'; };
}

#main
for my $package ( qw(Some Over Plain) ) {
my $instance = $package->new();
$instance->func;
}


runnig the code gives:

func from Some
func from Over
func from Plain


e.g. the
func
method is redefined in both cases, without any warning or such.

The questions:


  • are here some meaningful differences between the two ways?

  • when I should use the
    override
    and when the plain redefine?

  • is this discussed in some doc?


Answer

The documentation answers this perfectly.

override ($name, &sub)

An override method is a way of explicitly saying "I am overriding this method from my superclass". You can call super within this method, and it will work as expected. The same thing can be accomplished with a normal method call and the SUPER:: pseudo-package; it is really your choice.

Comments