How can I override a parent class function with child one in Perl?

偶尔善良 提交于 2020-01-03 09:22:08

问题


I would like to replace parent function (Somefunc) in child class, so when I call Main procedure it should fail.

Is it possible in Perl?

Code:

package Test;

use strict;
use warnings;

sub Main()
{
    SomeFunc() or die "Somefunc returned 0";
}

sub SomeFunc()
{
    return 1;
}

package Test2;

use strict;
use warnings;

our @ISA = ("Test");

sub SomeFunc()
{
    return 0;
}

package main;

Test2->Main();

回答1:


When you call Test2->Main(), the package name is passed as the first parameter to the called function. You can use the parameter to address the right function.

sub Main
{
    my ($class) = @_;
    $class->SomeFunc() or die "Somefunc returned 0";
}

In this example, $class will be "Test2", so you will call Test2->SomeFunc(). Even better solution would be to use instances (i.e., bless the object in Test::new, use $self instead of $class). And even better would be to use Moose, which solves a lot of problems with object-oriented programming in Perl.




回答2:


In order for inheritance to work you need to call your functions as methods, either on a class or an object, by using the -> operator. You seem to have figured this out for your call to Test2->Main(), but all methods that you want to behave in an OO way must be called this way.

package Test;

use strict;
use warnings;

sub Main
{
    my $class = shift;
    $class->SomeFunc() or die "Somefunc returned 0";
}

sub SomeFunc
{
    return 1;
}

package Test2;

our @ISA = ("Test");

sub SomeFunc
{
    return 0;
}

package main;

Test2->Main();

See perlboot for a gentle introduction and perltoot for more details.

Also, don't put parens after your subroutine names when you declare them -- it doesn't do what you think.



来源:https://stackoverflow.com/questions/2305386/how-can-i-override-a-parent-class-function-with-child-one-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!