Perl: print back to the beginning of the line

Okay, so I'm trying to print a percentage full of my command line, now I would just like to โ€œupdateโ€ the number shown on the screen. So, somehow back to the beginning of the line and change it.

For example, the windows command-line relog.exe utility (which can convert a .blg file to a CSV file) does this. If you run it, it will display the percentage of completion.

Now it is probably written in C ++. I don't know if this is possible in perl?

+6
command-line perl
source share
4 answers

Use the octal button "\ r" or "\ 015" (otherwise "Return caret" aka " " Carriage Return ", originating from the days of a typewriter:)

> perl5.8 -e 'print "11111\r222\r3\n";' 32211 > perl5.8 -e 'print "11111\015222\0153\n";' 32211 

Just remember to print at least as many characters as the longest line already printed to overwrite all old characters (as you can see in the example above, discarding it will contain old characters).

Another thing to be aware of is, as Michael pointed out in the communique, to enable autorun while these prints occur, so that the output does not wait for a newline at the very end of processing.

UPDATE: Please note that in the third answer 03, the eighth character is a vertical tab:

 > perl5.8 -e 'print "11111\013222\0133\n";' 11111 222 3 
+13
source share

Depending on what you would like to do, pv might solve your problem. It can wrap any script that takes a file as input, and adds a progress bar.

for example

 pv data.gz | gunzip -c | ./complicated-perl-script-that-reads-stdin 

pv packaged for RedHat / CentOS and Ubuntu as a minimum. Additional information: http://www.ivarch.com/programs/pv.shtml

Otherwise, I would use CPAN, for example. Term :: ProgressBar .

+8
source share

You can also use \ b to move one character:

  local $ |  = 1;  #flush immediately
 print "Doing it - 10%";
 sleep (1);
 print "\ b \ b \ b";
 print "20%";
 print "\ n", "Done", "\ n";
+1
source share

In C and C ++, the trick is to print char # 13. Perhaps it can work in Perl.

 for (int pc = 0 ; pc <= 100 ; ++pc) printf("Percentage: %02d %% %c", pc, 13); printf("\n"); 
0
source share

All Articles