Thursday, March 22, 2007
Monday, March 19, 2007
Perl quiz
What does the following Perl script output? (See the comments for the answer.)
#!/usr/bin/perl
use strict;
use warnings;
my $priority = '0009';
print $priority + 1;
print "\n";
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:
And finally here's the output:
This is bad.xml:
#!/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);
}
<metadata>And this is good.xml:
<file name="hello.file">
Simon & Garfunkel
</file>
</metadata>
<metadata>
<file name="hello.file">
Simon & 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'
}
};
Perl exits in XML::Simple module
I'm using the perl module XML::Simple on a boatload of XML files that apparently do not all validate. When this happens, the code just exits with an error:
Problem is, I don't want the code to exit. I want the code to ignore the problematic XML file, and skip to the next one. Can this be done? I tried using the Error module, but it did not help. Sample code:
Here's the output:
Bummer, the thing just gags on the first hit of the invalid xml file, displayed here:
Invalid name in entity [Ln: 3, Col: 15]
Problem is, I don't want the code to exit. I want the code to ignore the problematic XML file, and skip to the next one. Can this be done? I tried using the Error module, but it did not help. Sample code:
#!/usr/bin/perl
use strict;
use warnings;
use Error qw(:try);
use XML::Simple;
my $ii;
for ($ii = 0; $ii < 10; $ii++) {
try {
my $loc = "/tmp/test.xml";
my $xmldata = XMLin($loc);
print "got data\n";
} catch Error with {
print "problem\n";
my $ex = shift; # Get hold of the exception object
} finally {
print "finishing\n";
}
}
Here's the output:
wereldmuis@hostname:~$ perl testing.pl
finishing
Invalid name in entity [Ln: 3, Col: 15]
Bummer, the thing just gags on the first hit of the invalid xml file, displayed here:
<metadata>
<file name="hello.file">
Simon & Garfunkel
</file>
</metadata>