Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/articles/perl-tutorials/)
-   -   Progress Bar in Perl (http://www.go4expert.com/articles/progress-bar-perl-t17880/)

pradeep 6Jun2009 11:58

Progress Bar in Perl
 

Introduction



We all write programs to run on the terminal to do jobs that take time, like processing logs, sending out newsletter, etc. To know the progress of our task we print some messages to know our program is running well and doing its job. But wouldn't it be nice if we could add a progress bar to keep track of the completion of the task like wget, curl, etc.

Here's how we can do it in Perl, we'll use the perl module Term::ProgressBar to build and update the progress bar.

The Code



A very simple example:

Code: Perl

#!/usr/bin/perl

$| = 1;

use Term::ProgressBar;
use Time::HiRes qw/usleep/;

my $number_of_entries = 2000;
my $progress = Term::ProgressBar->new ({count => $number_of_entries ,name => 'Sending'});

for(1..$number_of_entries)
{
    usleep(650);
    $progress->update($_);
}


The output:

Code:

[root@deepzdev test]# ./prg_bar.pl
Sending:  40% [=======================================                                  *]

If you like to print some message and/or show an time estimate of the remaining time, here's another example:

Code: Perl

#!/usr/bin/perl

$| = 1;

use Term::ProgressBar;
use Time::HiRes qw/usleep/;

my $number_of_entries = 10;
my $progress = Term::ProgressBar->new ({count => $number_of_entries ,name => 'Sending',ETA=>'linear'});

for(1..$number_of_entries)
{
    sleep(5);
    $progress->update($_);
    $progress->message("\rSent $_ of $number_of_entries");
}

The output

Code:

[root@deepzdev test]# ./prg_bar.pl
Sent 1 of 10
Sent 2 of 10
Sending:  20% [===================                            ]0m40s Left

You can find more advanced option of the module at cpan.org

shabbir 2Jul2009 11:21

Re: Progress Bar in Perl
 
Nomination for article of the month - Jun 2009 Started. Nominate this article for Article of the month - Jun 2009

riyan 13Oct2010 22:27

Re: Progress Bar in Perl
 
how to install perl on pc my pc OS windows

pleaes help me

thamk you

PradeepKr 25Nov2011 20:33

Re: Progress Bar in Perl
 
Nice.
Suppose I have a program which runs for say 20 mins and want to show progress bar that. In this what would be $number_of_entries?

pradeep 26Nov2011 14:59

Re: Progress Bar in Perl
 
Generally, progress bar is used to show the progress of the operations being performed not the time, but if you want number_of_entries will be 20 which is for 20 mins, you should increment the progress bar every 1 minute.

PradeepKr 27Nov2011 13:36

Re: Progress Bar in Perl
 
Let me reframe my query.
Suppose I have a program which run for some time (I dont know the exact time).
Now I want to show the progress. Now what should be the input to your program?


All times are GMT +5.5. The time now is 13:56.