Emacs, scripting and anything text oriented.

Assigning a hash to another hash

Kaushal Modi

A hash can be assigned to a key of another hash using hash reference.

For a hash %HASH, it’s reference is obtained by \%HASH.

In the below example, the %fruit_colors and %veg_colors are assigned to the %food_colors hash.

use Data::Dumper;

my %food_colors = (
                   Fruits     => undef,
                   Vegetables => undef
                  );

my %fruit_colors = (
                    Apple  => "red",
                    Banana => "yellow"
                   );

my %veg_colors = (
                  "Green pepper"  => "green",
                  Potato          => "white"
                 );
print Dumper(\%food_colors);
print Dumper(\%fruit_colors);
print Dumper(\%veg_colors);

$food_colors{Fruits}     = \%fruit_colors;
$food_colors{Vegetables} = \%veg_colors;
print Dumper(\%food_colors);