views:

170

answers:

2

Hi,

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  A: 

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.

friedo
+1  A: 

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.

Lukáš Lalinský
Thank you, it works ;)
Miollnyr