http://www.perlmonks.org?node_id=879431


in reply to Re: xml simple not a hash reference
in thread xml simple not a hash reference

Thank you for the responses. This is my code:

my $results = $res->content; $xml = new XML::Simple (KeyAttr => [],suppressempty => 1,ForceArray => + ['roomtype']); $data = $xml->XMLin("$results"); foreach $e (@{$data->{data}->{bb}->{roomtypes}->{roomtype}}){ $roomtypename=$e->{roomtypename}; $rateid=$e->{mealtypes}->{mealtype}->{rateid}; }

I only receive the error when trying to get the value of rateid for the mealtype, if it is more than one, and I don't know how to loop through the mealtypes

Replies are listed 'Best First'.
Re^3: xml simple not a hash reference
by Anonyrnous Monk (Hermit) on Dec 28, 2010 at 15:00 UTC
    I don't know how to loop through the mealtypes

    The same way you're looping through the roomtypes:

    for my $mealtype ( @{$e->{mealtypes}->{mealtype}} ) { $rateid = $mealtype->{rateid}; }

    but don't forget to apply ForceArray to mealtype, too; or check with ref if $e->{mealtypes}->{mealtype} is an array reference, and only loop in that case (otherwise, you'd get an error if there's only one mealtype entry, in which case XML::Simple (without ForceArray in effect) would not create an extra array...)

      Thanks, I am almost there. I am using the following code:

      my $type = ref( $e->{mealplans}->{mealplan} ); if ($type eq "ARRAY") { $mealplans=$e->{mealtypes}->{mealtype}; for my $mealtype ( @{$e->{mealtypes}->{mealtype}} ) { $rateid = $mealtype->{rateid}; print "$mealtype"; } }

      It prints out: HASH(0x27acfbc)HASH(0x27acfcc) How do I get the Array readable?

        It prints out: HASH(0x27acfbc)
        This indicates that your $mealtype variable does not hold a scalar or array, but a reference to a hash.

        The easiest way to print that is probably to use Data::Dumper:

        use Data::Dumper; print Dumper($mealtype);

      This is what I am getting

      $VAR1 = { 'defaultmealplan' => 'true', 'rates' => { 'pax3' => '1180.00 +', 'pax2' => '930.00', 'pax4' => '1405.00', 'pax1' => '550.00' }, 'me +alplandesc' => 'Bed & Breakfast', 'rateid' => '6' }; $VAR1 = { 'rates' => { 'pax3' => '850.00', 'pax2' => '700.00', 'pax4' +=> '975.00', 'pax1' => '450.00' }, 'mealplandesc' => 'Self-catering', + 'rateid' => '7' };

      It is sorted out now! Thank you very much for all the help

      Thanks, I am almost there. I used the following code:

      my $type = ref( $e->{mealtypes}->{mealtype} ); if ($type eq "ARRAY") { for my $mealtype ( @{$e->{mealtypes}->{mealtype}} ) { $rateid = $mealtype->{rateid}; print "$mealtype"; } }

      However now I getting HASH(0x279d04c)HASH(0x279d05c). How do get the array in a readable state?