驼鹿类通过延伸

时间:2016-04-28 22:09:35

标签: perl moose

我想从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进行扩展(角色的运行时初始化)

    • 成功允许其他脚本导入模块
    • 禁止修改角色方法,因为它尚未在继承层次结构中

技术细节

  • Activestate Perl 5.16.3 Win64
  • Moose 2.1005
  • WWW :: Mechanize :: TreeBuilder 1.1003

FIX

  • 将Moose升级至2.1605
  • 通过CPAN将WWW :: Mechanize :: TreeBuilder升级到1.20

1 个答案:

答案 0 :(得分:1)

<强>症状

  • 使用&#34;&#34;

    进行扩展
    • 为模块文件中的代码工作
    • 在编译时通过&#34;使用&#34;
    • 导入模块时失败
  • 使用BUILD进行扩展(角色的运行时初始化)

    • 成功允许其他脚本导入模块
    • 禁止修改角色方法,因为它尚未在继承层次结构中

观察

  • Activestate Perl 5.16.3 Win64
  • Moose 2.1005
  • WWW :: Mechanize :: TreeBuilder 1.1003

FIX

  • 将Moose升级至2.1605
  • 通过CPAN将WWW :: Mechanize :: TreeBuilder升级到1.20