Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Does your XML::Simple code pass the strict test?

by grantm (Parson)
on Dec 09, 2002 at 09:21 UTC ( [id://218480]=perlmeditation: print w/replies, xml ) Need Help??

Version 2.0 of XML::Simple has just been released. The major version number increment is because this is the first stable version with SAX support, but today's essay has nothing to do with SAX. A new feature in this release is 'strict mode' which you can enable like this:

use XML::Simple qw(:strict);

Let's toss it into a simple test script ...

use strict; use XML::Simple qw(:strict); my $xml =q(<?xml version='1.0'?> <library> <book> <isbn>0596001320</isbn> <title>Learning Perl, 3rd Edition</title> <author>Randal L. Schwartz</author> <author>Tom Phoenix</author> </book> <book> <isbn>1565922204</isbn> <title>Advanced Perl Programming</title> <author>Sriram Srinivasan</author> </book> <book> <isbn>076455106X</isbn> <title>Guitar for Dummies</title> <author>Mark Phillips</author> <author>John Chappell</author> </book> </library> ); my $library = XMLin($xml); foreach my $book (@{$library->{book}}) { print "$book->{title}\n"; print " $_\n" foreach(@{$book->{author}}); }

When we run this script, instead of the expected list of book titles, we get this message:

No value specified for 'forcearray' option in call to XMLin() at ./str +icttest.pl line 26

A closer look at the foreach loop reveals that the test script assumes $library->{book} is an arrayref (which it is) and that each $book->{author} is also an arrayref (which the second is not). Now XML::Simple doesn't know what assumptions your script is making, but it does know that failing to specify an explicit value for the forcearray option can lead to dangerous assumptions just like the ones in our script.

The simplest way to get past this error is to set forcearray => 1. Unfortunately this will have the undesirable side-effect of turning $book->{title} into an arrayref too. A better solution is to set forcearray to a list of the element names which should be forced to an array representation - even if they occur only once:

my $library = XMLin($xml, forcearray => [ qw(book author) ]);

Now if we run the script, it fails again but with a new message:

No value specified for 'keyattr' option in call to XMLin() at ./strict +test.pl line 26

Once again, XML::Simple has detected a common mistake - failing to explicitly enable or disable the 'array folding' feature.

If we wanted to select a particular <book> record by its <isbn> we could have explicitly asked for the array of <book>s to be 'folded' into a hash using <isbn> as the key:

my $library = XMLin($xml, forcearray => [ qw(book author) ], keyattr => { book => 'isbn' } ); print $library->{book}->{1565922204}->{title}, "\n";

But, we actually wanted to loop through all the <book>s in the order they occurred in the XML, so we'll put back the original loop code and explicity disable array folding like this:

my $library = XMLin($xml, forcearray => [ qw(book author) ], keyattr = +> [] );

Now the code runs with no more errors and produces the expected output:

Learning Perl, 3rd Edition Randal L. Schwartz Tom Phoenix Advanced Perl Programming Sriram Srinivasan Guitar for Dummies Mark Phillips John Chappell

Those are the two most common errors, but if we revisit the array folding version we'll use strict mode to catch a more subtle problem:

my $library = XMLin($xml, forcearray => [ qw(author) ], keyattr => { book => 'isbn' } ); print $library->{book}->{1565922204}->{title}, "\n";

This time the script will die with this error:

<book> set in keyattr but not in forcearray at ./stricttest.pl line 26

In fact, without strict mode this version of the script would work exactly as expected. There is a lurking problem though that will leap out and bite us if the XML is changed to include only one <book>. Without 'book' listed in the forcearray list, the lone <book> element would be represented as a single hashref (rather than an array of hashrefs) and would therefore not be 'folded' into a hash keyed on <isbn>. The answer is simple - any elements you want folded should be listed in both the keyattr hash and the forcearray array.

Another type of data error can also be trapped by strict mode. Consider what would happen if you wanted the list of <book>s folded on the <isbn> values, but one of the <isbn>s was missing. Without strict mode, XML::Simple would issue a warning (which you may or may not see) and then leave the <book>s as an array rather than folding to a hash - which would most likely break whatever code followed. With strict mode, your script will die with a fatal error message when the bad data is encountered.

As you can see, strict mode is not magic - it can't tell you when your code is wrong, but (like 'use strict') it can trap common causes of problems. An obvious question is "why not just enable this behaviour when 'use strict' is in force?". The problem of course is that most people are already including 'use strict' in their scripts (you are doing that right?) so upgrading to version 2.0 would appear to break many scripts. Instead, the developer can upgrade and then enable XML::Simple's strict mode one script at a time - fixing any problems as they are detected.

Edit: s/30/26/g - dvergin 2002-12-09

Replies are listed 'Best First'.
Re: Does your XML::Simple code pass the strict test?
by grantm (Parson) on Dec 11, 2002 at 10:04 UTC

    Release 2.01 of XML::Simple has just been uploaded to CPAN. Release 2.00 had a rather silly bug which caused XMLout() not to work - ironically only when strict mode was enabled :-(

    Kudos to Ville Skytta for reporting the problem. On the bright side, it did give me the opportunity to add some more tests and thats always fun - Test::More rocks!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://218480]
Approved by gjb
Front-paged by grinder
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-12-02 17:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found