3

Perl中的这个eval语句有什么问题?我试图通过使用XML::LibXML捕获从文件解析中抛出的任何异常来检查 XML 是否有效:

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 $@;
4

2 回答 2

13

很简单, $tree 不会持续超过eval {}. perl 中的大括号作为一般规则总是提供一个新的范围。警告要求您提供其参数 $@。

my $tree;
eval { 
    # parses the file contents into the new libXML object.
    $tree = $parser->parse_file($file)
};
warn $@ if $@;
于 2010-01-12T04:22:15.063 回答
5

您在大括号内声明了一个 $tree,这意味着它在右大括号之后不存在。尝试这个:

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: $@") if $@;
于 2010-01-12T04:26:48.110 回答