Printing status displays in Perl scripts

While developing a Perl script this weekend to summarize Solaris zone usage, I wanted to display some type of status while my script did it’s thing. My friend Clay came up with a cool way to do this, and I thought I would share it here in case others needed to do something similar. Here is the code:

#!/usr/bin/perl -w

# Initialize the index.
my $index=0;

# The characters to use as spinners.
my @spinners = ("-", "\\", "|", "/");
my $totalspinners =  $#spinners + 1;

# Turn on autoflush.
$| = 1;

print "Factoring primes:  ";

while (1) {
    print "\\b$spinners[$index++ % $totalspinners]";
    sleep 1;
}

# If you were to exit the loop, turn off autoflush.
$| = 0;

There may be a better way to do this (adding an additional module isn’t an option), but I have yet to find it. Niiiiiice!

2 Comments

Clayton Scott  on November 10th, 2007

You can get rid of your $totalspinners variable altogether since an array in scalar context will give up the number of elements. Also autoflush is not controlling the loop, so your last comment is incorrect.


#!/usr/bin/perl -w

# Initialize the index.
my $index=0;

# The characters to use as spinners.
my @spinners = ("-", "\\", "|", "/");

# Turn on autoflush.
$| = 1;

print "Factoring primes: ";

while (1) {
print "\\b$spinners[$index++ % @spinners]";
sleep 1;
}

# If you were to exit the loop, turn off autoflush.
$| = 0;

hammami  on March 23rd, 2011

You have an error in your code in this line
print “\\b$spinners[$index++ % @spinners]“;
You must replace by
print “\b$spinners[$index++ % @spinners]“;

Leave a Comment