Possible Duplicate:
How do I create a hash of hashes in Perl?
I need to create something which is an equivalent of map : name(string) to map date(string/int) to value, i.e. a map { string => map { string => value } } .
How should i go about it in perl ?
The following code does not work.
my %strtomap_;
# given $str_, $date_, $val_
if ( ! exists $strtomap_ { $str_ } )
{
my %new_map_date_to_val_ ;
$new_map_date_to_val_{$date_} = $val_;
$strtomap_ { $str_ } = %new_map_date_to_val_ ;
}
else
{
$strtomap_ { $str_ } { $date_ } = $val_;
}
Values of aggregate types (hashes and arrays) can only be scalars, not other aggregate types. So if you are going to explicitly use something like your
%new_map_date_to_val_, you need to store a reference to it instead:though you can use an anonymous hash instead:
And in fact, the whole exists test is not needed, since simply dereferencing an undefined value in this kind of way will autovivify a hash reference for you. Your whole code can just be: