开发者

What's wrong with this eval statement in Perl?

开发者 https://www.devze.com 2022-12-15 22:25 出处:网络
What\'s wrong with this eval statement in Perl?I\'m trying to check that the XML is valid by catching any exceptions thrown from the parsing of the file with XML::LibXML:

What's wrong with this eval statement in Perl? I'm trying to check that the XML is valid by catching any exceptions thrown from the parsing of the file with XML::LibXML:

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

    eval { 
    my $tree = $parser->parse_file($file) # parses the file conten开发者_开发百科ts into the new libXML object.
    };
    warn() if $@;


Easy, $tree doesn't persist past the eval {}. Braces in perl as a general rule always provide a new scope. And warn requires you to provide its arguments $@.

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


You're declaring a $tree inside the braces, which means it doesn't exist past the closing brace. Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消