这个在 Perl 中的 eval 语句有什么问题?

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 $@;
2个回答

13

很容易,$tree在eval {}之后不会保留。在Perl中,花括号作为一般规则总是提供新的作用域。而warn需要你提供它的参数$@。

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

4
不需要单独声明$tree变量。eval的结果将是最后一个被评估的表达式的值:my $tree = eval { ... }。 - brian d foy

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接