Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?
like image 463
cajwine Avatar asked Apr 16 '16 18:04

cajwine


People also ask

How do you pass arguments to a subroutine in Perl?

Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

How do you call a subroutine from another file in Perl?

If you have subroutines defined in another file, you can load them in your program by using the use , do or require statement. A Perl subroutine can be generated at run-time by using the eval() function. You can call a subroutine directly or indirectly via a reference, a variable or an object.

What is Perl subroutine?

A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again.


1 Answers

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.

like image 57
ikegami Avatar answered Sep 28 '22 06:09

ikegami