Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Comment on

( #3333=superdoc: 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 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 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 ./ 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

In reply to Does your XML::Simple code pass the strict test? by grantm

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others taking refuge in the Monastery: (3)
    As of 2016-06-28 07:24 GMT
    Find Nodes?
      Voting Booth?
      My preferred method of making French fries (chips) is in a ...

      Results (350 votes). Check out past polls.