I am parsing xml files in Perl and everything seems to work great with one issue. I have files with the same schema, but they are returning different types of data from the parser. Here is a simplified example:
<tests>
<test>
<data1>Hi</data1>
<data2>Hello</data2>
</test>
<test>
<data1>Hi2</data1>
<data2>Hello2</data2>
</test>
</tests>
In a dump, this returns the following: (Take note of test being an array of two hashes)
$VAR1 = {
'test' => [
{
'data2' => 'Hello',
'data1' => 'Hi'
},
{
'data2' => 'Hello2',
'data1' => 'Hi2'
}
]
};
Now, for a similar set of data, but with only one 'test' entity like so:
<tests>
<test>
<data1>Hi</data1>
<data2>Hello</data2>
</test>
</tests>
This returns similar data, EXCEPT the test entity is no longer an array, but a singular hash:
$VAR1 = {
'test' => {
'data2' => 'Hello',
'data1' => 'Hi'
}
};
My dilemma is that my code expects an array there, as that is the norm. But on the slim chance when there is only one entity, it will return a hash for that entity. My question is, how can I handle the hash entity as though it were an array. Or test for it?
Right now my code for retrieving the array is like this:
foreach $test (@{$data->{'tests'}->{'test'}})
{
do something with $test
}
But with the hash, it gives an error "Not an ARRAY reference". I hope this is enough detail! Thanks!!!