Turn on autoflushing ($|=1;) and return the carriage (\r) instead of moving to a new line (\n). | [reply] [d/l] [select] |
I would put the '\r' at the beginning not the end of the line:
print "\r$_/5" foreach (1..5);
# and then:
print "\n"; # or print ' 'x10, "\n";
This places the cursor at the end of the line not at the start. In this small example this does not make any difference but if the loop takes a second or so to process the cursor will be visible. Also following lines would overwrite the last line otherwise, which is not always wanted.
| [reply] [d/l] |
You might look at the source code for Smart-Comments.
You might not use the module, but you're sure to learn something about making progress bars. It has a variety of progress bar styles.
Cheers! | [reply] |
system(($^O eq 'MSWin32') ? 'cls' : 'clear');
print "$_/5\n" foreach (1..5);
| [reply] [d/l] |
You attempt to clear the entire screen / tty / window / whatever just to overwrite a single line? I don't think that this is what the OP *really* wanted.
And by the way, your code is not portable: Not all non-Win32 platforms implement a clear command that clears the screen.
Assuming that STDOUT or STDERR write to a screen / tty / window is also wrong. Another user may run the program with STDOUT redirected to /dev/null to get rid of the anoying progress messages (think of a Makefile), and the program randomly cleans the screen, often including the entire scrollback buffer. All output from other programs running before is lost. In cron jobs or other non-interactive environments, you usually don't want progress messages, but just results or errors reported back. Imagine a cron job that tells you in 10.000 lines that it has just processed 0.01% of the job, 0.02% of the job, 0.03% of the job, 0.04% of the job, 0.05% of the job, ..... 99.99% of the job, 100.00% of the job.
Progress indicators can be useful. But you don't want them unconditionally. I would prefer a command line switch to enable or disable them, and a reasonable default, i.e. no progress indicator when STDOUT and/or STDERR aren't ttys (-t STDOUT / -t STDERR).
Alexander
--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
| [reply] [d/l] [select] |
Is something like the below one??? But it is not good solution (if prints for large number) as it is executing the system function for every print.
ikegami++ has given perfect solution. :-)
update: removed the code. Wrong solution.
| [reply] |