【问题标题】:Can't use string as a hash ref..?不能使用字符串作为哈希引用..?
【发布时间】:2011-12-19 00:14:31
【问题描述】:

我正在尝试为 Web 索引程序解析 HTML 文档。为此,我使用HTML::TokeParser

我的第一个 if 语句的最后一行出现错误:

 if ( $token->[1] eq 'a' ) {
     #href attribute of tag A
     my $suffix = $token->[2]{href};

上面写着Can't use string ("<./a>") as a HASH ref while "strict refs" in use at ./indexer.pl line 270, <PAGE_DIR> line 1.

我的问题是(后缀?或<./a>?)是一个字符串,需要变成一个哈希引用吗?我查看了其他有类似错误的帖子..但我仍然对此不确定。感谢您的帮助。

sub parse_document {

    #passed from input
    my $html_filename = $_[0];

    #base url for links
    my $base_url = $_[1];

    #created to hold tokens
    my @tokens = ();

    #created for doc links
    my @links = ();

    #creates parser
    my $p = HTML::TokeParser->new($html_filename);

    #loops through doc tags
    while (my $token = $p->get_token()) {
        #code for retrieving links
        if ( $token->[1] eq 'a' ) {
            # href attribute of tag A
           my $suffix = $token->[2]{href};

            #if href exists & isn't an email link
            if ( defined($suffix) && !($suffix =~ "^mailto:") ) {
                #make the url absolute
                my $new_url = make_absolute_url $base_url, $suffix;

                #make sure it's of the http:// scheme
                if ($new_url =~ "^http://"){
                    #normalize the url
                    my $new_normalized_url = normalize_url $new_url;

                    #add it to links array
                    push(@links, $new_normalized_url);
                }
            }
        }

        #code for text words
        if ($token->[0] eq 'T') {
            my $text =  $token->[1];

            #add words to end of array
            #(split by non-letter chars)
            my @words = split(/\P{L}+/, $text);
        }
    }

    return (\@tokens, \@links);
}

【问题讨论】:

  • 我会打印出一些调试语句,以通过 Data::Dumper($token) 准确查看它认为 token 是什么,并查看 $token->[1] 是什么。可能是 ' 或类似的东西弄乱了值。

标签: perl indexer


【解决方案1】:

$token->[2] 是字符串,而不是哈希引用。

执行print $token->[2],你会看到它是一个包含</a>的字符串

【讨论】:

    【解决方案2】:

    get_token() 方法返回一个数组,其中 $token->[2] 是一个包含您的 href 的哈希引用,仅当 $token->[0] 是一个 S(即开始标记)时。在这种情况下,您将匹配一个结束标记(其中$token->[0] 是一个 E)。详情请见PerlDoc

    要修复,请添加一个

    next if $token->[0] ne 'S';
    

    在循环的顶部。

    【讨论】:

    • 谢谢!我想我可以省略对开始标签的检查,因为我真的不明白它的用途。但我想这里需要使用中断。
    【解决方案3】:

    显然$token->[2] 正在解析为值为"</a>" 的哈希引用。肯定不是你想要的!

    【讨论】:

    • 其实$token->[2]是一个字符串("</a>"),他正试图使用它作为哈希引用。
    猜你喜欢
    • 2018-04-06
    • 2014-03-31
    • 2019-06-11
    • 1970-01-01
    • 2013-12-28
    • 2021-09-23
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多