I have written a function that is a countdown timer.
I want to print this way, Starts in 00:05
Hence I did this, but it doesn’t print correctly, it overwrites my sentence. Can you help fix it?
printf("\nStarts in %02d:%02d",countdownsleep(5));
# Sub for countdown
sub countdownsleep {
my $x = shift;
my $t = 1 *$x;
my ($m,$s);
my $stoptime = time + $t;
while((my $now = time) < $stoptime) {
#printf( "%02d:%02d\r", ($stoptime - $now) / 60, ($stoptime - $now) % 60);
$m = ($stoptime - $now) / 60;
$s = ($stoptime - $now) % 60;
select(undef,undef,undef,1);
}
return ($m,$s);
}
The problem is that you are using
\r(carriage return) – it returns the carriage to the very start of string (thus overwriting the first 5 characters in the best case scenario); AND causes weird printing behavior in the absence of “\n” (thus possibly not printing anything else after 5 characters).To fix your problem, you need to do this in your loop inside countdownsleep ():
And in your call:
Here is why you need to print “\n” at the VERY END
In other words, printing a carriage return (
\r) at the end of the string WITHOUT newline (\n) will effectively not print the string at all – more specifically, will erase everything that was suppose to be printed.Printing (
\r) before some other characters in the string will cause the subsequent characters to be printed from the beginning of the line, overwriting existing characters (as many as the new ones), but will keep the subsequent characters intact – with the caveat that the non-overwritten characters won’t be printed unless\nis printed at the end.print "$something\r"; # prints nothingprint "$something\r$finish"; # prints $finish but not $somethingprint "$something\r$finish\n";On a different note, you should consider using existing coundown/progress CPAN modules instead of rolling your own.