On Sep 30, 7:37 pm, [email protected] (Jon Hermansen) wrote:
> Hey all,
> I have this block of code:
>
> sub is_valid_xml {
>
> > my ($content) = @_;
>
> > eval {
> > my $xs = XML::Simple->new();
> > my $ref = $xs->parse_string($content);
> > };
>
> > return 1 unless ($@);
> > }
>
block eval will already trap fatal errors and set
$@ and return the undefined value or an empty
list depending on context. If there's no error,
then the value of the last expression evaluated
is returned. See: perldoc -f eval
So, one possibility:
sub is_valid_xml {
my ($content) = @_;
my $ret = eval {
my $xs = XML::Simple->new();
my $ref = $xs->parse_string($content);
1; # ensure true value if no fatalities
};
return $ret;
}
then just call the sub in scalar context and
check for an error:
is_valid_xml( "blah") or die "invalid: $@";
> and when I pass in 'blahblahblah' as an argument, I get:
>
> syntax error at line 1, column 0, byte 0 at /usr/lib/perl5/XML/Parser.pm
>
> > line 187
>
> I would like to trap this syntax error, but don't know how. I've tried each
> of these statements individually:
>
> local $SIG{'__DIE__'};
>
> > local $SIG{'__WARN__'};
> > no warnings 'all';
check 'perldoc -f eval' for additional info if you're trying to
trap warnings too.
--
Charles DeRykus
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/