in reply to Re: Calculating the average on a timeslice of data
in thread Calculating the average on a timeslice of data

Thanks for the reply and explanation. The reason I was thinking using an if statement is because there are 120 desired dates that I need to calculate an average for, and I didn't want to include 120 if statements in my code. Also the file being read in may be updated each week with new data and new dates, so ideally I wouldn't have to go back into the code and add new if statements to get the average for the new dates
  • Comment on Re^2: Calculating the average on a timeslice of data

Replies are listed 'Best First'.
Re^3: Calculating the average on a timeslice of data
by Tanktalus (Canon) on Jul 06, 2011 at 16:24 UTC

    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:

    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
    And this produces output like this:
    Date | Average 0109 | 5 0209 | 5.5 0309 | 8