不能将字符串用作哈希引用..? [英] Can't use string as a hash ref..?

查看:248
本文介绍了不能将字符串用作哈希引用..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to parse an HTML document for a web indexing program. To do this I'm using HTML::TokeParser.

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

I'm getting an error on the last line of my first if statement:

 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>?)是一个字符串,需要将其转换为哈希引用吗?我看了其他有类似错误的帖子..但是我仍然不确定.感谢您的帮助.

Is my problem that (the suffix? or <./a>?) is a string and needs to be turned into a hash ref? I looked at other posts that had similar errors.. but I'm still not at all sure about this. Thanks for any help.

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);
}

推荐答案

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

The get_token() method returns an array where $token->[2] is a hash reference containing your href only if $token->[0] is an S (that is, a start tag). In this case, you are matching an end tag (where $token->[0] is an E). See the PerlDoc for details.

要修复,请添加

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

位于循环的顶部.

这篇关于不能将字符串用作哈希引用..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆