Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl HTML::parser error; Undefined subroutine &main::1

I am getting the error

Undefined subroutine &main::1 called at /usr/local/lib/perl/5.10.0/HTML/Parser.pm line 102.

Here is my code

#open (IN,  "<", "foo.html") or die "can't open source file: $!";

my $p = HTML::Parser->new( api_version => 3,
            start_h => [&start, "tagname, attr, text"],
            text_h  => [&text,  "text"],
            default_h   => [sub { print OUT shift }, "text"],
        );
$p->utf8_mode;
$p->empty_element_tags;
$p->ignore_elements(qw(br));

$p->parse_file("foo.html") or die "parsing failed: $!";
#while (<IN>) {
#    $p->parse($_) || die "parsing failed: $!";
#}
#$p->eof;
#close IN;

As you can see in the commented out parts I have also tried directly opening and calling parse (with equally little luck).

The file does open fine.

Parser.pm line 102 which is error mentions is the parse_file subroutine, specifically the line calling ->parse

I have no clue where parse is, it is not in HTML::Parser nor did I find it in HTML::Entities the only dependency HTML::Parser has. =/ I am afraid I am lost at this point, the deepest magics of PERL are still a mystery to me.

like image 280
Nick Johnson Avatar asked Mar 22 '26 08:03

Nick Johnson


2 Answers

Try using \&start and \&text:

my $p = HTML::Parser->new( api_version => 3,
        start_h => [\&start, "tagname, attr, text"],
        text_h  => [\&text,  "text"],
        default_h   => [sub { print OUT shift }, "text"],
    );

Otherwise you are passing the result of calling start() and text(), not references to them as subs.

like image 116
ErikR Avatar answered Mar 24 '26 23:03

ErikR


In the documentation it says you should use \&start. If you exclude the backslash, it will be using the return value from the function start instead (which will be using the @_ as argument list, as per normal subroutine calling pragma using the &). This value could be 1.

Here is an example:

C:\perl>perl -we "$c=\&s; sub s { print 'yada' }; $c->();"
yada
C:\perl>perl -we "$c=&s; sub s { print 'yada' }; $c->();"
Undefined subroutine &main::1 called at -e line 1.
yada

Not sure why the error turns up there, but you might change it, see if it helps.

Oh, also, it does seem like you are not using use strict. When using strict, I get a much more helpful error:

C:\perl>perl -we "use strict; my $c=&s; sub s { print 'a' }; $c->();"
Can't use string ("1") as a subroutine ref while "strict refs" in use at -e line
like image 22
TLP Avatar answered Mar 25 '26 01:03

TLP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!