On Thu, Sep 30, 2010 at 8:34 PM, C.DeRykus <dery...@gmail.com> wrote:
> On Sep 30, 7:37 pm, jon.herman...@gmail.com (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 <http://learn.perl.org/> > > Charles, Thanks for the help. I was able to find a few workarounds with your examples. I found something interesting in my testing-- at the end of my sub, if instead of: return 1 unless ($@); > I use: if (not $@) {return 1;} > OR return 1 if (not $@); > the syntax error does not get printed out. I assumed that these statements were logically equal, so, what gives?