Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 726
Miollnyr Avatar asked Feb 21 '10 09:02

Miollnyr


2 Answers

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.

like image 194
Lukáš Lalinský Avatar answered Oct 01 '22 12:10

Lukáš Lalinský


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.

like image 25
friedo Avatar answered Oct 01 '22 10:10

friedo