Saturday, October 30, 2010

Perl action indicator using Term::Cap

If you are wondering how to make one of those whirling "I'm doing something" indicator on a screen in Perl, here is some code that will get you going. There are many libraries out there, but for those of you in companies where they won't let you use just any old CPAN library, here is a Termcap version which is standard with all Unix/Linux distributions of Perl.

use Term::Cap;
use POSIX;

# Load terminal IO library
my $termios = new POSIX::Termios;
# Get terminal settings
$termios->getattr;
# Get terminal speed
my $ospeed = $termios->getospeed;

$|=1;
$terminal = Tgetent Term::Cap { TERM => undef, OSPEED => $ospeed };
$terminal->Trequire(qw/ce ku kd/);

# Array for spinning thingy
my @seq=qw(| / - | \ -);
my $count=0;

# Position on the screen left to right (0 being left of screen)
my $x = 0;
# Position on the screen top to bottom (0 being top of screen)
my $y = 10;

while (1)
{
$terminal->Tputs('cl',1,*STDOUT); # Clear screen
$terminal->Tputs('cd',1,*STDOUT); # Clear data

# Set cursor position on screen
$terminal->Tgoto('cm',$x,$y,*STDOUT);
# Print one of the chars | / - \
print "$seq[$count++]";
sleep 1;
if ( $count > 5 )
{
$count = 0;
}
}

No comments:

Post a Comment