我想从WWW :: Mechanize创建一个消耗WWW :: Mechanize :: TreeBuilder角色的类,如果主代码位于同一模块文件中,这样可以正常工作。
package My::Mechanize;
use Moose;
use MooseX::NonMoose;
extends 'WWW::Mechanize';
with 'WWW::Mechanize::TreeBuilder' => {
tree_class => 'HTML::TreeBuilder::XPath'
};
has json => (
is => 'ro',
isa => 'JSON',
default => sub { JSON->new; },
lazy => 1,
handles => [ qw(encode decode)]
);
no moose;
1;
# main code here works fine
将主代码移动到另一个脚本,即
use My::Mechanize;
给我一个编译错误:
Can't use string ("My::Mechanize") as a HASH ref while "strict refs"
in use at reader My::Mechanize::tree (defined at
c:/Perl64/site/lib/WWW/Mechanize/TreeBuilder.pm line 167) line 5.
BEGIN failed--compilation aborted at D:\scripts\pdf.pl line 2.
我做错了什么?那是什么解决方案?非常感谢。
我也尝试用MooseX :: InsideOut替换Moose。它死在同一个地方有不同的信息(可能是同一个问题)
Use of uninitialized value in hash element at reader My::Mechanize::tree
(defined at c:/Perl64/site/lib/WWW/Mechanize/TreeBuilder.pm line 167)
Use of uninitialized value in hash element at reader My::Mechanize::tree
(defined at c:/Perl64/site/lib/WWW/Mechanize/TreeBuilder.pm line 167)
Use of uninitialized value in hash element at reader My::Mechanize::tree
(defined at c:/Perl64/site/lib/WWW/Mechanize/TreeBuilder.pm line 167)
Cannot delegate import to import because the value of tree is not defined at
c:/Perl64/lib/Moose/Meta/Method/Delegation.pm line 99.
My::Mechanize::import("My::Mechanize") called at D:\scripts\pdf.pl line 1
main::BEGIN() called at D:\scripts\pdf.pl line 1
eval {...} called at D:\scripts\pdf.pl line 1
看起来我需要初始化"树",我不知道如何:)
替代方法:这似乎对我有用
sub BUILD {
WWW::Mechanize::TreeBuilder->meta->apply(shift,
tree_class => 'HTML::TreeBuilder::XPath');
}
症状
使用""
进行扩展使用BUILD进行扩展(角色的运行时初始化)
技术细节
FIX
答案 0 :(得分:1)
<强>症状强>
使用&#34;&#34;
进行扩展使用BUILD进行扩展(角色的运行时初始化)
观察
FIX