Bts Bts - 10 months ago 124
Perl Question

How does the '\b' character in perl work?

According to my research the '\b' character used in perl print statements should act like a "backspace", that is, moving the cursor one character back, and deleting the current character. For this reason, I had planned to use this operation to print operational status on a single line, updating as it progressed. However, I noticed that while the cursor does indeed move back, the characters underfoot are not deleted, and therefore, longer messages remain after shorter print statements. I have compiled the following sample code to explain my findings:

#!/usr/bin/perl

use strict;
use warnings;
my $m;

#set to nonzero so that the screen will update before \n
local $| = 1;

print "Current number shown: ";

$m = "LONG MESSAGE TEMP";
print $m;
print "\b" x length($m);

foreach(1..22) {
$m = $_;
print $m;
print "\b" x length($m);
#sleep 1; #Uncomment to see updates
}

print "\n";


And this was the output:

Current number shown: 22NG MESSAGE TEMP


If this is indeed the correct operation of '\b', is there another escape that deletes the character as well as moving the cursor back? I would like to avoid using '\r' which starts at the beginning of the current line. Otherwise, how am I using the escapes incorrectly?

Answer Source

"\b" is just a fancy way of writing chr(0x08). Your terminal will likely move the cursor rather than display anything, but that's entirely up to it.

If you can rely on it, then you can achieve what you want by overwriting with spaces.

my $last_length = 0;
sub update {
   my ($s) = @_;
   print("\b" x $last_length);
   print(" " x $last_length);
   print("\b" x $last_length);
   print($s);
   $last_length = length($s);
}

Or with less flicker:

my $last_length = 0;
sub update {
   my ($s) = @_;
   my $diff = $last_length - length($s);
   print("\b" x $last_length);
   print($s);
   print(" " x $diff);
   print("\b" x $diff);
   $last_length = length($s);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download