Perl通过ISA继承

时间:2014-08-13 19:21:20

标签: perl inheritance packages

使用@ISA关于Perl继承的问题: 输入 - 3个文件:一个是主脚本,两个包含父和子。子包,相应地:

主:

#!/usr/bin/perl

use child qw(parent_or_child_function srictly_parent_function);

parent_or_child_function();
srictly_parent_function();

parent.pm:

package parent;

sub srictly_parent_function
{
    print "this is strictly parent function\n";
}

sub parent_or_child_function
{
    print "this is parent function which can be inherited\n";
}

1;

child.pm:

package child;

our @ISA = 'parent';

use Exporter qw(import);
@EXPORT_OK = qw(parent_or_child_function srictly_parent_function);

sub parent_or_child_function
{
    print "this is child function that replaced parent's\n";
}

1;

输出是:

 $main
this is child function that replaced parent's
Undefined subroutine &child::srictly_parent_function called at main line 6.

我做错了什么?我知道子包没有strict_parent_function,但是不应该搜索子的@ISA包吗?

1 个答案:

答案 0 :(得分:1)

首先,让父实际上成为一个对象。

package parent;
use strict;
use warnings;

# Constructor
sub new {
    my ($proto) = @_;
    my $class = ref($proto) || $proto;
    my $self = {};

    # Bless is what casts $self (instance of this class) as an object
    return bless($self, $class);
}

sub srictly_parent_function {
    my ($self) = @_;
    print "this is strictly parent function\n";
}

sub parent_or_child_function {
    my ($self) = @_;
    print "this is parent function which can be inherited\n";
}

1;

然后以parent作为对象,child可以继承

package child;

use strict;
use warnings;

# I prefer use base, as it's safer than pushing classes into @ISA
# See http://docstore.mik.ua/orelly/perl2/prog/ch31_03.htm)
use base qw(parent);

sub parent_or_child_function {
    my ($self) = @_;
    print "this is child function that replaced parent's\n";
}

# To give an example for accessing variables from a class.
my $variable = "WHATEVER";
sub get_variable { return $variable;}

1;

然后测试你的代码:

perl -e "use child; $object = child->new(); $object->parent_or_child_function();"

或正确编写脚本;

# Load up child class
use child qw();

# Invoke constructor to create an instance of the class
my $object = child->new();

# Invoke function from child class
$object->parent_or_child_function();

# Get Variable
$object->get_variable();