Reputation: 8602
I have a variable $i
that goes from 1 to 100. Is it possible to have the page display the # dynamically replacing the # that was there before?
Suppose I have the following code:
#!/usr/bin/perl
my $i = 0;
for my $i ('1' .. '10') {
print "$i";
sleep(1);
}
How do I make it so instead of print "12345...", it just replaces the # that was there before. So 1
becomes 2
, 2
becomes 3
, etc
Upvotes: 0
Views: 154
Reputation: 2297
"\r" returns the cursor to the beginning of the line. Instead, you probably just want to backspace the last printed number, and print the next one... Something like this:
$| = 1;
my $i = 0;
while ($i < 10) {
print $i;
sleep 1; # REPLACE WITH WHATEVER PROCESS YOU NEED TO DO
print "\b" x length $i++;
}
The last line of the while
loop prints a backspace the same length of the number it just printed, and then increments it. This is because the postfix ++
increments after evaluation.
Upvotes: 2
Reputation: 385867
For something simple like that, you can just move the cursor back using backspace or carriage return.
$| = 1; # Autoflush.
for my $i (1..10) {
print("\r", $i);
sleep(1);
}
print("\n");
Upvotes: 6