Updating multiple lines of perl output on terminal

Viewed 144

I am trying to update the progress of my Perl script on the terminal. The output looks something like this

  Progress: |||||||||            [46%]

The progress keeps on getting updated until it reaches 100%. This is being done by printing "\r" after updating the progress. I wish to update multiple lines at the same time, how can it be done? The expectation is something like this

  Progress: |||||||||            [46%]
  Run-time: 100sec

After some progress(and or time) I wish to update it like this

  Progress: ||||||||||           [50%]
  Run-time: 150sec

I tried printing "\r" two times to go to the previous line. But it didn't work.

I found similar questions (here and here), but they were answered for Python using modules. Mine is a Perl script, and I am not preferring to use external modules.

1 Answers

Term::ANSIScreen provides terminal control using ANSI escape sequences:

use Term::ANSIScreen qw!savepos loadpos!;

print savepos();
for my $i (1..10) {
    print '|' x $i, "\n";
    print "Step: $i\n";
    sleep 1;
    print loadpos();
}

or

use Term::ANSIScreen qw!up!;

for my $i (1..10) {
    print '|' x $i, "\n";
    print "Step: $i\n";
    sleep 1;
    print up(2);
}

These constants can be used instead of the module:

my $savepos = "\e[s";
my $loadpos = "\e[u";
my $up2 = "\e[2A";

ANSI escape codes

Related