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?