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

I'm trying to organize some data into one structure for reporting. I collate the data from parsing emails.

I have multiple sites, siteA, siteB etc and for each site there are dates and some dates repeated (the number of times I want to report).

I decided to create a hash of sites and the hash value for each site to be a hash of dates and the number of occurences. Basically I want my data to look like this...

( siteA => ('10-9-11' => 3, '11-9-11' => 1, '12-9-11' => 2), siteB => ('04-04-11' =>5, '05-05-11' =>1) )
I can create the initial entries and new sites and increment the date counter but I'm having trouble adding new dates to the hash reference.
my %h; # New site $h{'siteA'} = {'09-10-2011' => 1}; # Second instance of site and date found, increment. $a{'siteA'}->{'09-10-2011'}++; # Another date found for siteA, '10-10-2011' ...
Can someone please help me add a new hash date entry? I thought I could slice a hash reference but I can't get it working.

Replies are listed 'Best First'.
Re: Adding to a hash reference
by Marshall (Canon) on Dec 08, 2011 at 13:26 UTC
    Try this:
    #!/usr/bin/perl -w use strict; use Data::Dump qw(pp); my %h =( siteA => { '10-9-11' => 3, '11-9-11' => 1, '12-9-11' => 2 }, siteB => { '04-04-11' =>5, '05-05-11' =>1, } ); print "original:\n",pp(\%h),"\n"; $h{siteA}{'10-9-11'}++; $h{siteB}{'04-04-11'}+=55; $h{siteC}{'11-01-11'}=3; #Wow! print "Modifed Hash:\n",pp(\%h),"\n"; passing_hashref(\%h); sub passing_hashref { my $hashref = shift; $hashref->{SiteD}{'12-08-11'} = 33; } print "Modifed Hash via hashref subroutine:\n",pp(\%h),"\n"; __END__ original: { siteA => { "10-9-11" => 3, "11-9-11" => 1, "12-9-11" => 2 }, siteB => { "04-04-11" => 5, "05-05-11" => 1 }, } Modifed Hash: { siteA => { "10-9-11" => 4, "11-9-11" => 1, "12-9-11" => 2 }, siteB => { "04-04-11" => 60, "05-05-11" => 1 }, siteC => { "11-01-11" => 3 }, } Modifed Hash via hashref subroutine: { SiteD => { "12-08-11" => 33 }, siteA => { "10-9-11" => 4, "11-9-11" => 1, "12-9-11" => 2 }, siteB => { "04-04-11" => 60, "05-05-11" => 1 }, siteC => { "11-01-11" => 3 }, }
Re: Adding to a hash reference
by tobyink (Canon) on Dec 08, 2011 at 12:48 UTC
Re: Adding to a hash reference
by Anonymous Monk on Dec 08, 2011 at 13:27 UTC
      That replaces what was in $h{'siteA'} to start with. It doesn't add a new entry to the hash reference.

      The first answer looks good to me.