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

I am attempting to initialize the values of keys of hashes from a single hash. Instead of all the hashes being initialized by value, the values are all references to the same hash, which I don't want. What is the best way to set up all the hashes with the same structure/values of the one hash without just passing reference? In the example below, I would like the values of hash3 and hash4 to be the key/value pairs of hash1 and hash2. However, what I am getting is the values are being set to references, which means I cannot change the values of hash3 and hash4 independently.
use warnings; my %hash1 = ( bush => "A", tree => "A" ); my %hash2 = ( dog => "A", cat => "A" ); my %hash3 = ( plants => \%hash1, animals => \%hash2 ); my %hash4 = ( plants => \%hash1, animals => \%hash2 ); print "$hash3{plants}{bush}\n"; print "$hash4{plants}{bush}\n"; print "\n"; $hash4{plants}{bush}="B"; print "$hash3{plants}{bush}\n"; print "$hash4{plants}{bush}\n";

Replies are listed 'Best First'.
Re: Initial Hash of Hash by value
by wind (Priest) on Apr 07, 2011 at 18:25 UTC
    Create new anonymous hashes if you want the structures to be independent:
    my %hash3 = ( plants => {%hash1}, animals => {%hash2}, ); my %hash4 = ( plants => {%hash1}, animals => {%hash2}, );
Re: Initial Hash of Hash by value
by FunkyMonk (Bishop) on Apr 07, 2011 at 18:30 UTC
    You can easily create new references to your original hashes like so:

    my %hash3 = ( plants => { %hash1 }, animals => { %hash2 } ); my %hash4 = ( plants => { %hash1 }, animals => { %hash2 } );
Re: Initial Hash of Hash by value
by believer (Sexton) on Apr 11, 2011 at 13:06 UTC
    If you want to copy nested hashes, consider Storable dclone. For example, if %hash2 looks like this:
    %hash2 = ( mammal => { dog => 'a', cat => 'a' }, bird => {...}, ... )
    { %hash2 } will only copy the data 1 level deep. edit: removed link to perl cookbook