perl 中的继承在我的案例中显示错误

Inheritance in perl is showing a error in my case

我有两个 perl 模块 onee.pm 和 two.pm 以及一个 perl script.Following 是 one.pm

 package one;
sub foo
{
 print "this is one\n";
}
sub goo
{
 print "This is two\n";
}
1;

two.pm

package two;
use one;
@ISA=(one);
sub hoo
{
  print "this is three \n";
}
1;

inherit.pl

use two;
foo();

当我执行 inherit.pl 时出现以下错误。

 Undefined subroutine &main::foo called at inherit.pl line 2.

继承与此无关。您没有导出任何内容,因此 foo 子例程不在脚本的命名空间中。

事实上,您也在混淆面向对象的概念(继承)和 classic Perl 模块。如果你有一个非 oop 模块,你可以有导出器并将 subs 带入你的脚本。如果你有一个 class,你可以继承另一个 class。但是你通常不会导出任何东西。

现在,如果你想使用 twoone 导入一些东西,本质上是构建一些类似于通用函数的集合,你需要在 one 中使用 Exporter,然后two中的use one,然后使用two中的Exporter导出从one中导入的函数。

听起来很复杂?这样做是因为它很复杂。除非在脚本中保存一行 use one,否则这样做并没有真正的好处。

继承适用于对象。您要做的是导入,而不是继承。我在下面概述了继承和导入的示例。

继承:

One.pm:

package One;

sub foo {
    print "this is one\n";
}
1;

Two.pm:

package Two;

# Note the use of 'use base ...;'. That means that we'll inherit 
# all functions from the package we're calling it on. We can override
# any inherited methods by re-defining them if we need/want

use base 'One';

sub new {
    return bless {}, shift;
}
1;

inherit.pl:

use warnings;
use strict;

use Two;

my $obj = Two->new;
$obj->foo;

正在导入:

One.pm:

package One;

use Exporter qw(import);
our @EXPORT_OK = qw(foo); # allow user to import the 'foo' function if desired

sub foo {
    print "this is one\n";
}
1;

Two.pm:

package Two;
use One qw(foo); # import foo() from One

use Exporter qw(import);
our @EXPORT_OK = qw(foo); # re-export it so users of Two can import it

1;

import.pl:

use warnings;
use strict;

use Two qw(foo);

foo();

请注意,在下一个 Perl 版本 (5.26.0) 中,@INC 将默认不包含当前工作目录,因此 use One;use Two; 如果那些模块文件在本地目录中,您必须添加 use lib '.';unshift @INC, '.'; 之类的。