8

I am trying to print progress in % in command prompt. But it is not working properly.

I want to print the progress as :: Status 10% Completed when 20% will complete it will show Status 20% Completed in that same place not in new line. Could you please help me.

Code::

$count++;
$per=($count/$total)*100;
print "\nStatus:  $per Completed.\r";
sleep 1;
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
r-developer
  • 517
  • 1
  • 8
  • 21
  • 1
    set $|=1; and remove \n before Status: btw Term::ProgressBar could be a good choice – hypo Jan 23 '14 at 09:33
  • See also: http://stackoverflow.com/questions/1466648/how-can-i-update-values-on-the-screen-without-clearing-it-in-perl/1466699#1466699 – charlesbridge Jan 23 '14 at 13:36

3 Answers3

22

The module Term::ProgressBar seems to be able to do what you're after.

Note, I haven't tried it.

Edit Well, out of curiosity, I have now tried a small script:

use warnings;
use strict;

use Term::ProgressBar;

my $total = 50;
my $progress_bar = Term::ProgressBar->new($total);


for my $i (1 .. $total) {

  sleep (1);

  $progress_bar->update($i);

}

It won't exactly print what you asked (eg Status nn% completed), instead, it does print a real progress bar, something like

  10% [=====                                              ]

Nevertheless, it seems to most simple and straight forward solution.

René Nyffenegger
  • 39,402
  • 33
  • 158
  • 293
4

You can do something like this:

use strict;
use warnings;

use Time::HiRes qw(usleep);
local $| = 1;

my @nums = 1 .. 20;

foreach my $c (@nums) {
  print "$c";
  usleep(100000);
  print ("\b" x length($c));
}
print "\n";
chrsblck
  • 3,948
  • 2
  • 17
  • 20
3

Small modification to the original code: \n and \r are removed and added autoflush and "\033[G" and \033[J

$|=1; #autoflush

$count = 0;
$total = 100;
while ($count != $total) {
   $count++; 
   $per=($count/$total)*100; 
   print "\033[JStatus: ${per}% Completed."."\033[G"; # man console_codes, ECMA-48 CSI sequences, "CHA"
   sleep 1
 }  
mms
  • 769
  • 8
  • 13