in reply to Time Totaling re-explained

Hmm, here's how I'd add times (stretched out a bit to make it easier to read) - probably not the most efficient but... TIMTOWTDI :)
my $time1 = '4:23'; my $time2 = '5:13'; my $total_time = add_times($time1,$time2); print "Total time: $total_time\n"; exit(0); sub add_times { # read in times sent my @times = @_; my ($hours,$mins); for (@times) { # get values for this time my ($this_hour,$this_min) = split /:/; # keep running total $hours += $this_hour; $mins += $this_min; } # no of hours stored in $mins $hours += int($mins/60); # remainder after deviding by 60 $mins %= 60; return "$hours:$mins"; }

With this sub being able to take as many times as you want to send to it...

cLive ;-)

Replies are listed 'Best First'.
Re: Re: Time Totaling re-explained
by Rhose (Priest) on Oct 25, 2001 at 17:03 UTC
    The only comment I would offer is to left pad your minutes with a zero.

    #-- Original return "$hours:$mins"; #-- Suggestion return $hours.':'.substr('00'.$mins,-2);

    To see the difference, run the supplied sample with times of 5:33 and 4:33.

    Update:

    return sprintf("%d:%02d",$hours,$mins);

    Just as good or better. *Smiles*

      Ah yes, good point - TIMTOWTDI, but I think sprintf is more your friend for this:
      return sprintf("%d:%02d",$hours,$mins);
      cLive ;-)