zerocred has asked for the wisdom of the Perl Monks concerning the following question:

Hi PMs
I'm processing XML (using XML::Simple) and find that one of the fields I process is sometimes duplicated and thus shows up as an array - sometimes...

I have solved it with the following snippet:-
if(ref($content->{'A'}) eq 'ARRAY'){ # this is an array so need the [0] in there $x=$content->{'A'}[0]{'R1'}{'T1'}{'S1'}, $y=$content->{'A'}[0]{'R1'}{'T1'}{'content'} . . # more dereferencing further along the tree }else{ # this is not an array $x=$content->{'A'}{'R1'}{'T1'}{'S1'}, $y=$content->{'A'}{'R1'}{'T1'}{'content'} . . # more dereferening further along the tree }
However - this duplicates the great big chunks of dereferencing code... When there are duplicates, I only need the first one so only need branches under $content->{'A'}[0]{etc}...

How to make it simpler without repeating code?
I tried using a string variable in place of the {A}[0] - something like :-
$ifarray = "{'A'}[0]" else $ifarray = "{'A'}"
but that didn't work.
Suggestions, comments and solutions welcome!
Thanks in advance.
z

Replies are listed 'Best First'.
Re: Test for array or hash - ok, but what to do about it?
by Fletch (Bishop) on May 17, 2009 at 16:16 UTC

    my $content_handle = ( ref( $content->{'A'} ) eq 'ARRAY' ) ? $content->{'A'}->[0] : $content->{'A'};

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Test for array or hash - ok, but what to do about it?
by Anonymous Monk on May 17, 2009 at 16:07 UTC
    use option ForceArray=>1 that ways you always use ->{A}[0]

      That would force you to handle all tags as arrays, including those that are never repeated. It's better to specify what tags can be repeated in ForceArray => [qw(A B D)]. Or use XML::Rules that gives you even more detailed control.

      Jenda
      Enoch was right!
      Enjoy the last years of Rome.

Re: Test for array or hash - ok, but what to do about it?
by zerocred (Beadle) on May 17, 2009 at 16:39 UTC
    great stuff - both great ideas! Thanks guys.... z