1

I'm parsing a XML file with XML::Simple using these options

my $xml = XML::Simple->new(ForceArray => 1, KeyAttr => 1, KeepRoot => 1);

This is a sample xml document

<ip>
    <hostname>foo</hostname>
    <info>server</info>
    <soluton>N/A</solution>
    <cats>
        <cat>
            <title>Baz</title>
            <flags>0</flags>
        </cat>
        <cat><title>FooBar</title></cat>
    </cats>
</ip>
<ip>
    <info>client</info>
    <diagnosis>N/A</diagnosis>
    <cats>
        <cat><title>Foo</title></cat>
        <cat>
            <title>Bar</title>
            <update>Date</update>
        </cat>
    </cats>
</ip>

As you can see, not every node has the hostname attribute, which causes my script to die with an "Can't use an undefined value as an ARRAY reference" error when I try to get the hostname

   $nb = "@{ $_->{hostname} }";

There are several optional elements in the xml (more than a dozen). How should I handle that? Should I check the existence of the element prior to the assignment?

if ( @{ $_->{hostname} ) { $nb = "@{ $_->{hostname} }" }
if ( @{ $_->{solution} ) { $s  = "@{ $_->{solution} }" }
if ( @{ $_->{diagnosis} ) {...}

Should I use an eval block?

eval { $nb = "@{ $_->{hostname} }" };

Maybe

eval {
    $nb = "@{ $_->{hostname} }";
    $s  = "@{ $_->{solution} }";
    $d  = "@{ $_->{diagnosis} }";
};

Is there a better way?

Tucan
  • 61
  • 4

1 Answers1

0

First at all, do you really need 'ForceArray' option enabled? Maybe it's better to use scalar values and check for arrays where they (possible) are?

Solutions for references to array that-may-be-undefined I use is:

my $string = join '', @{ $var || [] };

Which means "dereference variable or empty anonymous arrayref".

In your case it will be

$nb = join '', @{ $_->{hostname} || [] };
yko
  • 2,710
  • 13
  • 15
  • I enable the Force Array because the real xml is more complex than the example. (It's a Qualys Scan Report, with lots of nested elements and lists) – Tucan Oct 19 '11 at 08:35
  • @Tucan than solution above should help you. – yko Oct 19 '11 at 13:54