How do you delete or change the display on the last print on perl?

Viewed 102

What I'm trying to do it print out a string and then after a few background checks, change the previously said string?

So here is what it will initially look like:

#
Loading design modules....please wait.

Then after a few background checks it will remove "Loading design modules....please wait." then change it to something like this without clearing the whole CLI Screen:

#
Design module loaded!

This is my code so far:

#!/usr/bin/perl

use strict;
use warnings;
use diagnostics;

use feature 'say';
use feature 'switch';

use IO::Socket;
use Scalar::Util qw(looks_like_number);
use Term::ANSIScreen qw/:cursor :screen/;

$| = 1;
print "Loading design modules....please wait";
sleep(5);
say "Design module loaded!";
2 Answers

Use savepos() to save the position of the cursor and loadpos() to go back to that saved position.

Here's a first attempt:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Term::ANSIScreen ':cursor';

$| = 1;

savepos;

print "Loading design modules....please wait";
sleep 5;
loadpos;
say "Design module loaded!";

But as the second string is shorter than the first, we'll end up seeing bits of both string:

Design module loaded!s....please wait

The easiest solution is probably to just print a string of spaces to overwrite the first string before printing the second.

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Term::ANSIScreen ':cursor';

$| = 1;

savepos;

print "Loading design modules....please wait";
sleep 5;
loadpos;
print ' ' x 37;
loadpos;
say "Design module loaded!";

If you only need to rewrite that one line, then the \r character escape is enough

use warnings;
use strict;
use feature 'say';

$| = 1;

my $msg_init = "Loading design modules....please wait";

print $msg_init;

sleep 5;

say "\rDesign module loaded", ' ' x length $msg_init;

where I print spaces after the final message to make sure that the original one is overwritten.

The carriage return \r puts the cursor back at the beginning of the line, so this only works for the current line. It is commonly used to track progress of waiting, something like in this one-liner

perl -wE'$| = 1; for (1..5) { print "\rWorking ... $_ "; sleep 1 }; say "\ndone"'

(in which case the original message is left on the screen).

See this post for some ways to animate the cursor while waiting.

Related