我有以下软件包和文件:
Child.pm
package Child;
use Father; # this should automatically extends Father also
has 'name' => (is => 'rw', default => "Harry");
1;
Father.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
。
我在父的导入功能中放了一个代码,推送到子模块ISA,但没有用。
如何使这项工作,让父模块在导入过程中扩展子模块。
答案 0 :(得分:4)
package Child;
use Moose;
extends 'Father';
您只使用use
导入包,而不是继承该包。你在这里想要做的是一个黑客攻击,虽然你可能能够让它工作,但你会让它更难理解。特别是对于可能不得不处理代码的其他人。
答案 1 :(得分:0)
看一些导出模块,我找到了Import::Into,它非常有用并解决了这个问题。
以下是我解决问题的方法:
Child.pm
package Child;
use Father; # automatically extends Father also
has 'name' => (is => 'rw', lazy=>1, default => "Harry");
1;
Father.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