eval
Perl中的这个陈述有什么问题?我试图通过捕获使用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 $@;
Run Code Online (Sandbox Code Playgroud)
Eva*_*oll 13
容易,$ tree不会持续过去eval {}
.作为一般规则,perl中的大括号总是提供新的范围.警告要求你提供其参数$ @.
my $tree;
eval {
# parses the file contents into the new libXML object.
$tree = $parser->parse_file($file)
};
warn $@ if $@;
Run Code Online (Sandbox Code Playgroud)
你在大括号内声明了一个$ 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 $@;
Run Code Online (Sandbox Code Playgroud)