OnResolve
OnResolve

Reputation: 4032

Pushing a hash to an existing hash in Perl

I'm new to Perl, so you'll have to forgive my code.

I'm reading a file that tree structured (like xml, just not actually) and I want to foreach through the tree and if a certain "node" doesn't have a child node, I want to insert it. Simple enough.

Here's my code:

foreach $key ( @{$struct->{'transferBatch'}->{'callEventDetails'} } ) {

    foreach ( keys %{$key} ) {

        if ( $_ eq "mobileTerminatedCall" ) {

            if ( defined $key->{$_}->{'basicServiceUsedList'} ) {

                if ( defined $key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'} ) {

                    if ( not defined $key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'}[0]->{'CallTypeGroup'} ) {

                        $CallTypeGroup = {                          
                                "CallTypeLevel1:" => "0",
                            "CallTypeLevel2:" => "0",
                            "CallTypeLevel3:" => "0"

                        };                          

                        #Doesn't work! 
                        $key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'}[0]{'CallTypeGroup'} =  $CallTypeGroup;
                    }
                }
            }
        }
    }
}

The iteration is working fine, but my push call fails saying it's not an ARRAY reference. I feel like I'm close, but I need that line to insert the $CallTypeGroup hash as a child to the current spot.

Any help is appreciated!

Upvotes: 0

Views: 377

Answers (1)

ikegami
ikegami

Reputation: 386501

$key->{$_}->{'basicServiceUsedList'}[0]->{'chargeInformationList'}[0]

contains a reference to a hash, as created here (if not earlier):

if ( not defined
   $key->{$_}{basicServiceUsedList}[0]
      ->{chargeInformationList}[0]
         ->{CallTypeGroup} )

You did not indicate what data structure you want, so I'm not sure how we can help other than explain the message. I think you simply want to change that if to

if ( not defined
   $key->{$_}{basicServiceUsedList}[0]
      ->{chargeInformationList}[0] )

btw, you really should use variables to hold the intermediate references instead of having such long "names".

btw, I'm highly skeptical of all those hardcoded zero indexes.

Upvotes: 1

Related Questions