in reply to Timestamp doesn't work well

First, are you sure you've accurately transcribed the code you are running? If I run
#!/usr/bin/perl -w use strict; my $runtime = 3600; my $runtime2; my $nextruntime = 0; my $days = int($runtime / 86400); $runtime -= ($days * 86400); my $hours = int($runtime / 3600); $runtime -= ($hours * 3600); my $minutes = int($runtime / 60); my $seconds = $runtime % 60; $days = $days .'d '; $hours = $hours .'h '; $minutes = $minutes .'m '; $runtime2 = $runtime; $runtime2 = $days . $hours . $minutes . $seconds . 's'; if (time()>=$nextruntime){ $nextruntime=time()+300; $runtime += 300; print "Duration: $runtime2\n"; }
I get the output
Duration: 0d 1h 0m 0s
which corresponds with your spec but not your cited output. However, on the next iteration of your loop, I would get
Duration: 0d 0h 5m 0s
This issue happens because you are dropping hour and above information on every iteration of your loop. You need to choose if you are going to destructively parse your term, or use it as an accumulator. You'll have better luck with something like:
#!/usr/bin/perl -w use strict; my $start = time(); while (1) { my $buffer = (time() - $start); ($buffer, my $seconds) = (int $buffer/60, $buffer % 60); ($buffer, my $minutes) = (int $buffer/60, $buffer % 60); ($buffer, my $hours) = (int $buffer/24, $buffer % 24); my $days = $buffer; print "Duration: ${days}d ${hours}h ${minutes}m ${seconds}s\n"; sleep (300); }

As a side note, while(1) is incredibly abusive to system resources as you've implemented it. Take a look at sleep for implementing waiting in a script.


#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: Timestamp doesn't work well
by Jabox (Sexton) on Jun 30, 2014 at 15:55 UTC
    Ah wow thanks! Yeah your code makes perfect sense for this situation.. and I didn't think about the sleep part either.. ahahah