模块中的奇怪范围错误

时间:2014-05-28 07:36:37

标签: perl inheritance html-parsing

我正在编写一个继承自HTML :: Parser的Perl模块,我收到一个编译错误,我从昨天起就无法解决。这是代码:

#!/usr/bin/perl
# HTML::Parser : The inheriting module
# Fetches all links and their text from a HTML file

use warnings;
use strict;
use HTML::Entities;

package AnchorTextParser;

use base 'HTML::Parser';

our $betweenAnchor;
our $linkAdress;
our %anchorTexts;


sub start {
    my (undef, undef, $attr) = @_;
    if( $attr->{href} && not ($attr->{href} =~ /mailto/i) ) {
        $betweenAnchor = 1;
        $linkAdress = $attr->{href};
    }
}

sub end {
    $betweenAnchor = 0;
}

sub text {
    if( $betweenAnchor ) {
        my $origText;
        (undef, $origText) = @_;
        #print decode_entities($origText) . "\n";
        %anchorTexts{$linkAdress} = decode_entities($origText); 
    }
}

sub getAnchorTexts {
    return\%anchorTexts;
}

1;

加载模块时出现的错误是:

syntax error at AnchorTextParser.pm line 34, near "%anchorTexts{" 
Global symbol "$origText" requires explixit package name at AnchorTextParser.pm line 34.
syntax error at AnchorTextOarser.pm line 36, near "}"
Compilation failed in require at module_loader.pl line 6.
BEGIN failed--compilation aborted at module_loader.pl line 6. 

为了避免混淆,这就是模块加载器中发生的事情:

#!/usr/bin/perl
# HTML::Parser : The test script

use warnings;
use strict;
use AnchorTextParser;

这是我第一次在Perl中编写一个继承模块,所以很可能是我做错了什么。但错误是如此不明显而且显然是错误的($ origText不是全局的,并且非常清楚地定义为"我的#34; ..),我无法弄清楚错误是什么。 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

通过将anchorTexts更改为%来修复您对第34行$变量的引用:

    $anchorTexts{$linkAdress} = decode_entities($origText); 
相关问题