SingleLinePrinter
use SingleLinePrinter;
my $slp = new SingleLinePrinter( sub { sleep 1 } );
$slp->print($_) while <>;
SingleLinePrinter allows you to print multiple lines of text one after another into just one line on your screen.
It can be used to monitor longer activities like showing filesnames written to a backup, which would fill up your screen and and start to scroll if every filename would be written into a new line.
This could also be used to print moving bars or rotating cursors.
SingleLinePrinter does not only print the text, it also calls a user-specified function. You can use it as a wrapper around an existing function that does a lot of work and should be monitored (like the file archive routine mentioned above).
print() is called on this object. Default value is an empty anonymous
subroutine.
item FILEHANDLE
The filehandle to print to. The default is to use STDOUT. This value
should be passed as a glob reference, e.g. \*STDERR for STDERR.
The printed text will be cut off and aligned according to the values given on instanciation.
If no parameter is given, then no text is printed. If no or only one parameter is given, then the callback function is called without parameters.
A return value of the callback function is passed through and returned by print().
This piece of code reads text from stdin and prints it line by line to stdout, sleeping 1 second per line. It uses an anonymous subroutine which is called for every printed line to do the sleeping:
use SingleLinePrinter;
my $slp = new SingleLinePrinter( sub { sleep 1 } );
$slp->print($_) while <>;
This does the same, but without an anonymous subroutine:
use SingleLinePrinter;
sub callback {
sleep 1;
}
my $slp = new SingleLinePrinter( \&callback );
$slp->print($_) while <>;
In this example, only 10 characters are printed per line. Lines longer than 10 characters have only their last 10 characters printed. Output is sent to STDERR instead of STDOUT.
use SingleLinePrinter;
my $slp = new SingleLinePrinter(
sub { sleep 1 }, # CALLBACK
10, # MAXLENGTH: 10 chars
0, # LEFTBOUND: false = rightbound
\*STDERR # FILEHANDLE: STDERR
);
$slp->print($_) while <>;
In this example, the callback function expects parameters and returns something as well:
use SingleLinePrinter;
sub is_prime($) {
# check if given number is prime
# return number if prime
# return empty list of not prime
my $number = shift;
foreach my $j (2..($number/2)) {
return () if $number % $j == 0;
}
return $number;
}
my $slp = new SingleLinePrinter( \&is_prime );
my @primes;
foreach my $i (100000..105000) {
push @primes, $slp->print(
"checking $i", # text to print
$i # parameter for
# callback function
);
}
print "@primes\n";
SingleLinePrinter was written by Christian Garbs <mitch@cgarbs.de>.
An up-to-date version of this module can be found at <http://www.cgarbs.de/singlelineprinter.en.html>.
(c) 2005 by Christian Garbs SingleLinePrinter is licensed under the GNU GPL.