Search code examples
perlhtml-parsingwww-mechanizehtml-parser

Perl Error "Can't call method "get_tag" on an undefined value at Parser.pl line 6"


I wrote a simple perl script but i am getting this runtime error:

Can't call method "get_tag" on an undefined value at Parser.pl line 6

Below is my code:

#!usr/bin/perl
use HTML::TokeParser
my $p=HTML::TokeParser->new('bad.html');
while (my $token=$p->get_tag('a')){
my $url=$token->[1]{href};
print "$url\n";
}

I have placed a file bad.html under the same directory of this perl program. Below is the code for bad.html

<html><body>
<a href="https://www.Google.com">Google</a>
<a href="https://www.yahoo.com">Yahoo</a>
</body></html>

Please help me on the error in running my perl code.


Solution

  • The problem of not using:

    use strict;
    use warnings;
    

    They save you hours! You missed a ; in the line use HTML::TokeParser.

    You could write the script in a better way:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    use HTML::TokeParser;
    
    my $p = HTML::TokeParser->new('bad.html');
    while ( my $token = $p->get_tag('a') ) {
        my $url = $token->[1]{href};
        print "$url\n";
    }