Reputation: 1583
I've seen similar questions asked on here ad nauseum but none of those could answer my own question specifically.
I am trying to programatically create a hash of hashes. My problem code is as follows:
my %this_hash = ();
if ($user_hash{$uuid})
{
%this_hash = $user_hash{$uuid};
}
$this_hash{$action} = 1;
$user_hash{$uuid} = %this_hash;
my %test_hash = $user_hash{$uuid};
my $hello_dumper = Dumper \%this_hash;
According to my output, $this_hash is being assigned properly but
$user_hash{$uuid} = %this_hash
is showing a value of 1/8 in the debugger; not sure what his means. I'm also getting a warning: "odd number of elements in hash assignment..."
Upvotes: 2
Views: 559
Reputation: 239861
Any time you write
%anything = $anything
you're doing something wrong. Almost any time you write
$anything = %anything
you're doing something wrong. That includes when $anything
is an array or a hash access (i.e. $array[$index]
or $hash{$key}
). The values stored in arrays and hashes are always scalars, and arrays and hashes themselves aren't scalars. So, when you want to store a hash in a hash, you store a reference to it: $hash{$key} = \%another_hash
. And when you want to access a hash that's had a reference to it stored in a hash, you dereference: %another_hash = %{ $hash{$key} }
or $hashref = $hash{$key}; $value = $hashref->{ $another_key }
or $value = $hash{$key}{$another_key}
.
For getting up to speed with references I strongly recommend reading the Perl References Tutorial and the Perl Data Structures Cookbook.
Upvotes: 12
Reputation: 71525
It's not really a "hash of hashes"; it's a "hash of references to hashes".
Try:
$user_hash{$uuid} = \%this_hash;
Upvotes: 5