2010-01-12 5 views
3

Perl에서이 eval 문에 오류가 있습니까? 나는 XML은 XML::LibXML와 파일의 구문 분석에서 던진 예외를 잡기로 유효한지 확인하기 위해 노력하고있어 :Perl에서이 eval 문이 잘못되었습니다.

use XML::LibXML; 
my $parser = XML::LibXML->new(); #creates a new libXML object. 

    eval { 
    my $tree = $parser->parse_file($file) # parses the file contents into the new libXML object. 
    }; 
    warn() if [email protected]; 

답변

13

쉽고, $ 나무는 eval {}지나 지속되지 않습니다. 일반적으로 perl의 중괄호는 항상 새로운 범위를 제공합니다. 그리고 경고는 당신이 그것의 인수 $ @를 제공 할 것을 요구합니다.

my $tree; 
eval { 
    # parses the file contents into the new libXML object. 
    $tree = $parser->parse_file($file) 
}; 
warn [email protected] if [email protected]; 
+4

$ tree를 별도로 선언 할 필요는 없습니다. eval의 결과는 마지막 평가 결과입니다 : my $ tree = eval {...}. –

5

중괄호 안에 $ 트리가 있음을 의미합니다. 즉, 닫는 중괄호를 지나지 않아야합니다. 이것을 시도하십시오 :

use XML::LibXML; 
my $parser = XML::LibXML->new(); 

my $tree; 
eval { 
    $tree = $parser->parse_file($file) # parses the file contents into the new libXML object. 
}; 
warn("Error encountered: [email protected]") if [email protected];