Append dict in another dict in perl

Viewed 75

I am having dictionary like this.

print Dumper($emp)

$VAR1 = {
          'mike' => {
                      
                      'country' => {
                                     'US' => {
                                        'pop' => 100
                                     }
                                    }
                    }
        }

I want to append a new entry inside 'country' like this.

$VAR1 = {
          'mike' => {
                      
                      'country' => {
                                     'US' => {
                                        'pop' => 100
                                     },
                                     'Canada' => {
                                        'pop' => 101
                                     }
                                    }
                    }
        }

Right now I am building it like this

$emp -> {$name}{country} = getCountry();

sub getCountry{
  ....
  return country;
}
1 Answers

It's not clear what getCountry returns. Seeing as it's a single scalar, I'm going to assume it's a hash of countries keyed by name despite the name.

{ Canada => { pop => 101 } }

A simple way to merge two hashes is

%h = ( %h, %new );

so

%{ $emp->{$name}{country} } = (
   %{ $emp->{$name}{country} },
   %{ getCountry() },
);

If getCountry were to return the country's name and the country, you'd could use the following:

my ($country_name, $country) = getCountry();
$emp->{$name}{country}{$country_name} = $country;

So, if the hash returned by getCountry returns just a single country, you could also do the following without changing getCountry:

my ($country_name, $country) = %{ getCountry() };
$emp->{$name}{country}{$country_name} = $country;
Related