【问题标题】:Perl Moose extend child class from Parent by Use statementPerl Moose 通过 Use 语句从 Parent 扩展子类
【发布时间】:2014-08-05 22:10:38
【问题描述】:

我有以下包和文件:

孩子.pm

package Child;

use Father; # this should automatically extends Father also

has 'name' => (is => 'rw', default => "Harry");

1;

父亲.pm

package Father;

use Moose;

sub import {
    my ($class, @args) = @_;
    my ($caller, $script) = caller;
    my $package = __PACKAGE__;
    {
        no strict 'refs';
        @{"${caller}::ISA"} = ($package, @{"${caller}::ISA"});
        # tried this also
        #eval {"package $caller; use Moose; extends qw($package);1;"}
    }

}

1;

test.cgi

#!/usr/bin/perl

use Child;

my $child = Child->new;
print "child name: " . $child->name;

我想要包 Child 自动扩展包 Father

我在Father的import函数中放了一段代码来推送到子模块ISA但是没有用。

如何做到这一点,让父模块在导入过程中扩展子模块。

【问题讨论】:

  • 也许我没有按照您的想法进行操作,但是简单地使用 extends 有什么问题吗?
  • 使用扩展“父亲”;我必须在使用 Moose 之前使用它;所以我试图保存这一行输入
  • 我强烈反对你这样做。你省下来的打字线,在以后别人被你过分的聪明弄糊涂的时候,会得到几十倍的回报。

标签: perl moose


【解决方案1】:

使用Moose 关键字extends 而不是use

package Child;
use Moose;
extends 'Father';

您只是导入带有use 的包,而不是从它继承。你在这里试图做的是一个黑客,虽然你可以让它工作,但你让它更难理解。特别是对于其他可能必须处理代码的人。

【讨论】:

  • 使用扩展“父亲”;我必须在使用 Moose 之前使用它;所以我试图保存这一行输入
  • Moose 通过Class::MOP 发挥它的魔力,它确实需要加载才能发挥这种魔力(比如能够声明属性)。如果你没有以某种方式在课堂上useing 它,那么你就没有引入 Moose 需要的功能,而且它不会起作用。如果你想改变一些样板,也许可以使用Moops
【解决方案2】:

看了一些导出模块,发现Import::Into,很好用,解决了问题。

这是我解决问题的方法:

孩子.pm

package Child;

use Father; # automatically extends Father also

has 'name' => (is => 'rw', lazy=>1, default => "Harry");

1;

父亲.pm

package Father;

use Moose;
use utf8;

use Import::Into;
use Module::Runtime qw(use_module);

our @EXPORT_MODULES = (
        Moose => [],
    );

sub import {

    my ($class, @args) = @_;

    my ($caller, $script) = caller;

    my $package = __PACKAGE__;

    # ignore calling from child import
    return if ($class ne $package);

    my @modules = @EXPORT_MODULES;

    while (@modules) {
        my $module = shift @modules;
        my $imports = ref($modules[0]) eq 'ARRAY' ? shift @modules : [];
        use_module($module)->import::into($caller, @{$imports});
    }

    {
        no strict 'refs';
        @{"${caller}::ISA"} = ($package, @{"${caller}::ISA"});
    }

}

sub father {
    my $self = shift;
    return "Potter";
}

1;

test.cgi

#!/usr/bin/perl

use Child;

my $child = Child->new;
print "child name: " . $child->name, "\n";
print "father name: " . $child->father, "\n";

test.cgi 的输出:

child name: Harry
father name: Potter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 2020-12-15
    • 1970-01-01
    • 2013-03-15
    • 2013-10-23
    相关资源
    最近更新 更多