I often find myself working with statistics that are time-indexed, and as such I put the data into a hash with the time as the key. I just stumbled over this tidbit to shorten the code it takes to increment a time key. The code to extend this to days, months, and years gets really hairy (I will post it too if desired).
$start = "23:58:45"; $end = "00:01:15"; $key = $start; while ($key ne $end) { print "$key\n"; # perform action on $hash{$key} here ($h, $m, $s) = split(":",$key); (($s +=1) %=60) || (($m +=1) %=60) || (($h +=1) %=24); $key = join(":",map{sprintf("%02d",$_)}($h,$m,$s)); }

Replies are listed 'Best First'.
Re: time hash keys
by tadman (Prior) on Aug 04, 2001 at 08:41 UTC
    Maybe someone could be a real chum and write a ++/-- overload system that would allow you to add and subtract times? Date::Calc is great and all, but something more low level could come in handy now and then. Like a Date type with a full suite of arithmetic overloads.

    As for me, I prefer to use the UNIX time_t type times, which are 9/10 digit numbers and can represent an exact date and time, not just time. To iterate through them you could do something like:
    use Time::Local; for (timelocal(0,0,0,1,0,100)..timelocal(59,59,23,1,0,100)) { my ($s,$m,$h) = localtime($_); }
    That will go through the first day of January (month #0) of 2000 (year 1900+100), second by second. I'm using localtime to extract the HH:MM:SS data.

      You might want to check out Class::Date. I don't think it has ++/-- but it has pretty much everything else, AFAICT.

      bbfu
      Seasons don't fear The Reaper.
      Nor do the wind, the sun, and the rain.
      We can be like they are.