How to write a progress spinner in PERL
May 2, 2008 by mrtoothdecay
This is how to create a progress spinner in PERL. Concepts covered include: autoflush var, modulo operator, for loop, carriage return character.
1: local $|=1;
2: my @spinner = ('|', '/', '-', '\\');
3: for(my $i=0; $i <= 32; $i++)
4: {
5: print "Voila! ", $spinner[$i % 4];
6: print “\r”;
7: sleep 1;
8: }
9: print “\nDone!\n”;
Let’s look at the meaningful lines:
Line 1: local $| = 1;
This sets PERL’s print buffer to auto flush. This causes the print statements within the for-loop to be output to the screen as soon as they occur, instead of waiting for a newline. $| defaults to zero.
Line 2: my @spinner = (’|', ‘/’, ‘-’, ‘\\’);
A simple array to hold the crude, but sufficient, characters that will emulate a spinner.
Line 5: print “Voila! “, $spinner[$i % 4];
Since we have four pieces to our spinner, we’ll address each one in succession by using a modulo 4 calculation on the array index.
Line 6: print “\r”;
This prints a carriage return, which basically moves the cursor back to the beginning of the line. This causes each subsequent print to overwrite the previous one. In quick succession this creates the illusion we’re looking for.
Remember, there’s more than one way to do it!