Assigning a hash to a hash

10,351

Solution 1

Aggregates only store scalars. So use the ref operator to take a ref to the hash:

$nodes{$id} = \%node_hash;

or, sometimes slightly more safely, allocating a new one and copying the old one into it, then returning the new reference:

$nodes{$id} = { %node_hash };

Solution 2

A hash value must be a scalar, so you need to assign a hash reference:

$nodes{$id} = \%nodeHash;

Solution 3

You can't use a hash as the value, but you can use a reference to the hash; $nodes{$id} = \%nodeHash;

Share:
10,351
user494216
Author by

user494216

Updated on June 14, 2022

Comments

  • user494216
    user494216 almost 2 years

    Right now I have two hashes. I want to assign one entire hash to an id in a second hash. However, I am having trouble assigning that hash into the other hash.

    Can you assign a hash into another hash by just saying:

    $nodes{$id}=%nodeHash;
    

    Right now this doesn't work because when I say:

    print Dumper(\%nodes);
    

    I get this as a result:

    $VAR1 = {
          'c2' => '4/8',
          'c1' => {}
        };
    

    Sorry if this doesn't totally make sense, I am not a very experienced programmer so a hash of hashes is pretty complex.

    • hobbs
      hobbs over 13 years
      perlreftut perlreftut perlreftut
  • user494216
    user494216 over 13 years
    This is perfect. Fixed my problem!