What is wrong with this eval statement in Perl?

What happened to this expression evalin Perl? I am trying to verify that XML is valid by catching any exceptions obtained from parsing a file using 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 contents into the new libXML object.
    };
    warn() if $@;
+3
source share
2 answers

Easy, $ tree is not saved after eval {}. Brackets in perl, as a rule, always provide a new area. And the warning requires that you provide your arguments to $ @.

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

You declare $ tree inside curly braces, which means that it does not exist behind the closing bracket. Try the following:

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 $@;
+5
source

Source: https://habr.com/ru/post/1728134/


All Articles