in reply to Re^2: Calculating the average on a timeslice of data
in thread Calculating the average on a timeslice of data
Why would you have multiple if's? You don't hardcode things that vary - that's what variable means. You need a way to figure out what date(s) you want to gather averages for, which may be "all of them", and then vary on that. For example, if you want the user to specify the date, just make it a command line parameter: avg_for.pl 0109. Then you just set my $desired_date = shift @ARGV;, and the code I posted would suffice.
If you want to produce an average for ALL dates, you can use a hash to accumulate it, and then loop through the keys for the output:
And this produces output like this:use strict; use warnings; use Text::Table; my %totals; while (<DATA>) { my ($id, $date, $value) = split ' '; $totals{$date}{sum} += $value; ++$totals{$date}{count}; } my $tbl = Text::Table->new('Date', \' | ', 'Average'); for my $date (sort keys %totals) { $tbl->add($date, $totals{$date}{sum} / $totals{$date}{count}); } print $tbl; __END__ 1 0109 4 1 0209 5 1 0309 8 2 0109 6 2 0209 6
Date | Average 0109 | 5 0209 | 5.5 0309 | 8
|
|---|