note
tmoertel
<small>(<strong>Updated:</strong> Something bad happened to the code portion during cut-and-paste to the site. This is now fixed.)</small>
<p>Here's a quick bit of code that provides a simple, object-oriented
way to draw progress bars. To use it, just create a progress bar
like so:
<code>
my $bar = ProgressBar->new( width => 40 );
</code>
(Here, our bar will be 40 characters wide.) Then, to draw the
bar, just pass in the current count of completed tasks and the
total number of tasks:
<code>
$bar->draw( 3, 10 );
</code>
So, in the above example, we have completed 3 of 10 tasks and
the following would be drawn:
<code>
============ 30%
</code>
A couple of points:
<ul>
<li>If the total number of tasks is fixed, you can provide it at
the time you create the progress bar via the <code>max_val</code>
parameter and omit it in calls to
the <code>draw()</code> method.
<li>The code works properly for progress bars that go forward,
backward, or both. (See the demo.)
</ul>
<p>Here's the code:
<code>
#!/usr/bin/perl -w
{
# TGM 2004-10-05
# Progress bar code
package ProgressBar;
use Class::Struct width => '$', portion => '$', max_val => '$';
use List::Util qw( min );
sub draw {
local $| = 1;
my ($self, $x, $max_val) = @_;
$max_val ||= $self->max_val;
my $old_portion = $self->portion || 0;
my $new_portion = int( $self->width * $x / $max_val + 0.5 );
print "\b" x ( 6 + $self->width
- min( $new_portion, $old_portion ) )
if defined $self->portion;
print "=" x ( $new_portion - $old_portion ),
" " x ( $self->width - $new_portion ),
sprintf " %3d%% ", int( 100 * $x / $max_val + 0.5 );
$self->portion( $new_portion );
}
1;
}
# DEMO
my $pb = ProgressBar->new( width => 40, max_val => 10 );
# show progress 0 to 100% and then back down to 0% again
do { $pb->draw( $_ ) ; sleep 1 } for 0 .. 10;
do { $pb->draw( 9 - $_ ); sleep 1 } for 0 .. 9;
print "\n";
</code>
Hope this helps.
<p>Cheers,<br>Tom
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-109406">
<p><small><strong>Tom Moertel</strong> : <a href="http://community.moertel.com/">Blog</a> / <a href="http://community.moertel.com/ss/space/Talks">Talks</a> / <a href="http://search.cpan.org/~tmoertel/">CPAN</a> / <a href="http://community.moertel.com/LectroTest">LectroTest</a> / <a href="http://community.moertel.com/ss/space/PXSL">PXSL</a> / <a href="http://community.moertel.com/ss/space/A+Coder%27s+Guide+To+Coffee">Coffee</a> / <a href="http://community.moertel.com/ss/space/IMDB+Movie-Rating+Decoder+Ring">Movie Rating Decoder</a></small>
</div></div>
396839
396839