in reply to Calculations using values from two different hashes

Append this after all the calculations:

foreach my $date (keys %counts){ my $overallcount = $overallcounts{$date}; foreach my $word (keys %{$counts{$date}}){ $counts{$date}{$word."_average"} = sprintf("%.2f", 100 * $counts{$ +date}{$word} / $overallcount); } $counts{$date}{"_overallcount"} = $overallcount; } print Dumper \%counts;

Which yields:

$VAR1 = { '2017-09-30' => { 'c' => 1, 'b' => 2, 'a_average' => '57.14', '_overallcount' => 7, 'b_average' => '28.57', 'c_average' => '14.29', 'a' => 4 }, '2017-09-04' => { 'd' => 1, 'c_average' => '18.18', '_overallcount' => 11, 'b' => 3, 'a' => 5, 'b_average' => '27.27', 'd_average' => '9.09', 'c' => 2, 'a_average' => '45.45' } };

You can then replace {$word."_average"} with {$word} to overwrite the original values.

Replies are listed 'Best First'.
Re^2: Calculations using values from two different hashes
by Maire (Scribe) on Nov 25, 2017 at 13:13 UTC
    This works brilliantly, thank you very much! Just to double check that I've understood everything here, does the "%.2f" part of the code specify that only the first two decimal places should be returned?
      does the "%.2f" part of the code specify that only the first two decimal places should be returned?

      Yes.
      More strictly speaking the returned value will be the actual value, rounded to two decimal places in accordance with the rule "round to nearest, ties to even".
      C:\>perl -le "printf '%.2f', 0.245;" 0.24 C:\>perl -le "printf '%.2f', 0.255;" 0.26
      Cheers,
      Rob
        Ah, okay. Thanks!
      Hello Marie oops.. Maire,

      > Just to double check that I've understood everything here, does the "%.2f"..

      This is covered under sprintf documentation, specifically in the paragraph "precision, or maximum width".

      Anyway try it to see:

      # pay attention to MSWin32 double quotes! perl -e "printf qq($_\n),3.141592 for '%f','%.0f','%.1f','%.2f'" 3.141592 3 3.1 3.14

      L*

      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
        Ah, thanks for the link and the example. I'm going to have a play about with that now, thanks!