2011-08-19 34 views
3

我收到錯誤Perl HTML ::解析器錯誤;未定義子程序及主要:: 1

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

這裏是我的代碼

#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; 

正如你可以在註釋部分我還試圖直接打開並調用解析看(同樣運氣不多)。

該文件打開正常。

Parser.pm線102這是錯誤中提到的是parse_file子程序,特別是排隊叫號 - >解析

我不知道在那裏分析是,它不是在HTML解析器::也沒有我發現它在HTML :: Entities中,唯一的依賴HTML :: Parser具有。 = /恐怕我在這一點上迷失了,PERL最深的魔法對我來說仍然是個謎。

+0

你使用'use strict;使用警告;'? – TLP

+0

fwiw,method'parse'顯然是一個XS例程(即它在C中實現) – ErikR

回答

7

嘗試使用\&start\&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"], 
    ); 

否則你逝去的呼叫start()text(),而不是對它們的引用作爲潛艇的結果。

+0

感謝您的快速響應,它的工作! –

+0

是的,它工作,因爲它是正確的:) – vol7ron

3

在文檔中說它應該使用\&start。如果排除反斜槓,它將使用函數start中的返回值(它將使用@_作爲參數列表,如使用&的普通子例程調用編譯指示)。該值可能是1

下面是一個例子:

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 

不知道爲什麼錯誤就會來這裏,但你可能會改變它,看它是否有幫助。

哦,還有,它看起來好像你沒有使用use strict。當使用嚴格的,我得到一個更實用的錯誤:

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 
+0

謝謝,引用sub工作!嚴格被使用= /但這整個事情已經很奇怪,我只是很高興現在正在工作。 –

+0

@尼克約翰遜:嚴格的詞彙範圍;顯然HTML/Parser.pm不使用它 – ysth

+0

@ysth奇怪的是,HTML/Parser.pm使用嚴格。 – TLP