Tuesday, March 13, 2007

How to stop perl from exiting

Here's how to stop perl from exiting: use eval (a subset of the rule RTFM)! Here's some test code:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;
use XML::Simple;

my $loc = "/tmp/bad.xml";
my $xmldata = eval { XMLin($loc) };
if ($@) {
print "problem with xmldata in $loc, skip it\n";
} else {
print Dumper($xmldata);
}

$loc = "/tmp/good.xml";
$xmldata = eval { XMLin($loc) };
if ($@) {
print "problem with xmldata in $loc, skip it\n";
} else {
print Dumper($xmldata);
}
This is bad.xml:
<metadata>
<file name="hello.file">
Simon & Garfunkel
</file>
</metadata>
And this is good.xml:
<metadata>
<file name="hello.file">
Simon &amp; Garfunkel
</file>
</metadata>

And finally here's the output:

wereldmuis@hostname:~$ perl testing.pl
problem with xmldata in /tmp/bad.xml, skip it
$VAR1 = {
'file' => {
'content' => '
Simon & Garfunkel
',
'name' => 'hello.file'
}
};

Labels: , ,

0 Comments:

Post a Comment

<< Home