user2342605
user2342605

Reputation: 27

Overwrite all prints at the same place in perl

I want overwrite my all print result at the same place . It should not scroll. and I want it infinite time. For that I have used while(1) and it is working properly. But the problem is every time I print the statement , it scrolls down and that I want to change. I want it to print it or you could say overwrite it at the same place.

Could some please help me with this??

I also tried to use \r in both print statements but it only updates the last print statement at the same place.

while(1)
{
.... // some lines of code //

print("\n******** Interrupts *********\n");
for($k=0; $k<$t_intr; $k++)
{
    $intr_diff = $total_intr_curr[$k] - $total_intr_prev[$k];
    #push(@intr_diff_arr,$intr_diff);
    print("Intr : $intr_diff\n"); // want to update this print at same place //

}

print("\n******** Context switches *********\n");

for($l=0; $l<$t_ctxt; $l++)
{
   $cntx_min = 0;
    $ctxt_diff = $total_ctxt_curr - $total_ctxt_prev;
    push(@ctxt_diff_arr,$ctxt_diff);
    $min = min @ctxt_diff_arr;
    $max = max  @ctxt_diff_arr;
    print("Ctxt : $ctxt_diff Minimum : $min Maximum : $max\n"); // want to update this print also at same place //
}

}// infinite while loop end //

Thank you.

Upvotes: 0

Views: 819

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753990

Unless your terminal settings do something funny with mapping CR to NL, this should work:

#!/usr/bin/env perl
use strict;
use warnings;

$| = 1;

foreach my $i (1..20)
{
    print "\rLine $i";
    sleep 1;
}
print "\n";

Note the $| = 1; setting; that's necessary to get the output to appear. When it is deleted, I only got the last line of output visible, and that only after 20 seconds. However, a hex dump of the output showed that all the data was sent; it just that it only gets sent at the end, when the newline is printed.

Upvotes: 1

Related Questions