使用“覆盖”或只是简单地重新定义perl中的子例程

前端之家收集整理的这篇文章主要介绍了使用“覆盖”或只是简单地重新定义perl中的子例程前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有这个示例代码 – 2个包扩展了Some包并重新定义了func方法.

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代码给出:

func from Some
func from Over
func from Plain

例如在两种情况下都重新定义了func方法,没有任何警告等.

问题:

>这两种方式之间有一些有意义的差异吗?
>什么时候我应该使用覆盖和什么时候重新定义?
>这是在一些文档中讨论的吗?

解决方法

documentation完美地回答了这个问题.

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.

猜你在找的Perl相关文章