Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I move the cursor back of one position in a terminal?

I want to show an animation that alternate the character /, | and \.

How am I supposed to write always in the same cell of the terminal? I need to bring the cursor back of one position.

like image 821
Zagorax Avatar asked Dec 27 '22 21:12

Zagorax


2 Answers

Most terminals will handle a backspace (chr(8)) by moving the cursor back. The key is to disable buffering.

use Time::HiRes qw( sleep );

$| = 1;  # Disable buffering on STDOUT.

my $BACKSPACE = chr(0x08);

my @seq = qw( | / - \ );
for (;;) {
   print $seq[0];
   push @seq, shift @seq;
   sleep 0.200;
   print $BACKSPACE;
}

print "$BACKSPACE $BACKSPACE";
like image 196
ikegami Avatar answered Feb 07 '23 17:02

ikegami


An variant of ikegami's answer :)

use Time::HiRes qw(sleep);
$| = 1;  # Disable buffering on STDOUT ;)

for(1..10) {
    for (qw( | / - \ )) {
        print "$_\b";
        sleep 0.2;
    }
}
print
like image 44
jm666 Avatar answered Feb 07 '23 18:02

jm666