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

How to write a script to find average for time unig perl. the list of data will be in excel file with (Hr:Min:Sec) format.sample data are below. please provide an input.
2:11:20
2:07:44
2:18:41
0:40:17
2:40:53
1:27:21
4:03:43
1:54:42
1:59:40
2:08:49
2:12:21
23:45:31--Total Time
2:09:36--Avg Time

Replies are listed 'Best First'.
Re: Find average for time(Hr:Min:Sec)
by Anonymous Monk on Dec 29, 2009 at 06:14 UTC
    Try Time::Duration::Parse, Time::Duration, and List::Util:
    use strict; use warnings; use Time::Duration::Parse qw(parse_duration); use Time::Duration qw(duration); use List::Util qw(sum); my @times = <DATA>; my $count = @times; my $sum = sum map { parse_duration($_) } @times; my $avg = $sum / $count; print duration($sum, 3), "--Total Time\n"; print duration($avg, 3), "--Avg Time\n"; __DATA__ 2:11:20 2:07:44 2:18:41 0:40:17 2:40:53 1:27:21 4:03:43 1:54:42 1:59:40 2:08:49 2:12:21
    prints
    23 hours, 45 minutes, and 31 seconds--Total Time 2 hours, 9 minutes, and 35 seconds--Avg Time

    Or just split each string and do the math yourself. And be sure to check for blank or not-valid strings.

Re: Find average for time(Hr:Min:Sec)
by ww (Archbishop) on Dec 29, 2009 at 11:49 UTC
Re: Find average for time(Hr:Min:Sec)
by swampyankee (Parson) on Dec 29, 2009 at 19:33 UTC

    You've got an answer, with code, so I'm going to give you some generic advice.

    When you're being asked to average or total anything, your first step will be to convert everything to a standard unit (for time, I'd pick seconds), do the arithmetic with that unit, and then convert it to something that is easier for people to read (I'd be happy with an answer like 85 531 seconds, but that's just me). Obviously, some error checking is required, including the obvious checks to make sure that the H:M:S times don't include nonsense, like 4:103:99


    Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

Re: Find average for time(Hr:Min:Sec)
by lostjimmy (Chaplain) on Dec 29, 2009 at 15:12 UTC
    It's pretty easy to roll your own in this instance...
    my $total_time = 0; my $num_records = 0; while (<DATA>) { chomp; my ($hour, $min, $sec) = split /:/; $total_time += $hour * 3600 + $min * 60 + $sec; ++$num_records; } print format_time($total_time), "--Total Time\n"; print format_time($total_time/$num_records), "--Avg Time\n"; sub format_time { my $seconds = shift; my $hours = int($seconds / 3600); my $minutes = int($seconds / 60 - $hours * 60); my $sec = int($seconds - $hours * 3600 - $minutes * 60); sprintf "%02d:%02d:%02d", $hours, $minutes, $sec; }