Thursday, March 22, 2007

Perl quiz: case-sensitivity

What is the output of this Perl program (answer in comments)?


#!/usr/bin/perl

use strict;
use warnings;

my $a = 10;
my $A = 1;

print "$a + $A = " . ($a + $A) . "\n";

Labels: ,

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:

#!/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: , ,

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:
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>