Hello monks!
Is it possible to use hash reference as a key in another hash reference?
I realize I am looking for functionality that a database could give me easily but I have been using Perl hashrefs for log analysis and would like to continue that way.
In the below, simplified example I am keeping stats of sales at a burger joint. The hash that I would like to use as a key contains the date and time data (we'll call it the "key hash"). In a current, working system I have a function (basically a join) that is used to convert the "key hash" into a string that becomes the key used to store the sales data. Later on I have to use another function to convert that string back into a hash -- this is fine for homogenous data but I would like to use abstraction to allow dynamic "hash keys" and this idea seemed simpler than having the data carry around it's own transform functions.
I believe that am misunderstanding something fundamental about hash references because the code below seems to work. It takes the "hash key" hash reference and inserts the "stats hash" but when I try to reference the "hash key" I only have a "string" which of course throws up errors. I've tried to re-reference the hash but can't seem to find a way to do it properly.
thanks for whatever help you can provide
Results:use strict; use warnings; use Data::Dumper; my $key_hash_1 = { 'day' => 1, 'month' => 1, 'year' => 2000, 'hour' => + 4, 'minute' => 44}; my $key_hash_2 = { 'day' => 1, 'month' => 1, 'year' => 2000, 'hour' => + 4, 'minute' => 45}; my $sales_hash = { $key_hash_1 => {'burgers_sold' => 5, 'fries_sold' => 3, 'sodas_so +ld' => 11}, $key_hash_2 => {'burgers_sold' => 2, 'fries_sold' => 4, 'sodas +_sold' => 7} }; print Dumper($key_hash_1,$key_hash_2); print Dumper($sales_hash); while (my ($key_hash,$sales) = each (%$sales_hash)){ print "$key_hash => $sales\n"; while (my ($sales_item,$total_sold) = each(%$sales)){ print "\t$sales_item => $total_sold\n"; } while (my ($time_item,$time_value) = each(%${$key_hash})){ print "\t$time_item => $time_value\n"; } }
$VAR1 = { 'hour' => 4, 'minute' => 44, 'month' => 1, 'day' => 1, 'year' => 2000 }; $VAR2 = { 'hour' => 4, 'minute' => 45, 'month' => 1, 'day' => 1, 'year' => 2000 }; $VAR1 = { 'HASH(0x904d00)' => { 'fries_sold' => 4, 'sodas_sold' => 7, 'burgers_sold' => 2 }, 'HASH(0x815d48)' => { 'fries_sold' => 3, 'sodas_sold' => 11, 'burgers_sold' => 5 } }; HASH(0x904d00) => HASH(0x90c238) fries_sold => 4 sodas_sold => 7 burgers_sold => 2 Can't use string ("HASH(0x904d00)") as a SCALAR ref while "strict refs +" in use
In reply to Use a hashref as a key in another hashref? by mwb613
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |