[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1902
  • Last Modified:

Erasing characters using BackSpace

I'd like to perform a char-by-char login and password input. How can I display input properly when BackSpace key pressed? The current source is like the following, but it does not erase chars (I don't know how to do this). It should work in Unix, Win32 used for some testing only.

#!/usr/local/bin/perl
#
use Term::ReadKey;
use English;

my $s;

if ($OSNAME =~ /WIN32/i) {
    $ENTER = chr(13);
} else {
    $ENTER = chr(10);
}  

print "Password: ";
readstring($s, "*");
exit;

#**************************************
sub getchar {
    ReadMode 4;
    my $k;
    while(!defined ($k)) {
       $k = ReadKey(-1);
       next if (!defined ($k));
    }
    ReadMode 0;
    return $k;
}

#**************************************
sub readstring {
    my ($str, $passwordchar) = @_;
    my ($s) = "";
    my ($i_char) = "Empty";
    while ($i_char ne $ENTER) {

        $i_char = getchar();

        if (ord($i_char) == 8) {            # BackSpace
            $s = substr($s, 0, length($s)-1);
        } elsif ($i_char ne $ENTER) {
            print (defined $passwordchar ? $passwordchar : $i_char);
            $s .= $i_char;
        } elsif ($i_char eq $ENTER) {
        } else {
            print "Unknown character in line!\n";
        }
    }
    $_[0] = $s . "\n";
    return 0;      # normal completion
}

0
dda
Asked:
dda
1 Solution
 
b2piCommented:
\b is the backspace char, but it doesn't erase.  So follow it with a space. Try this:

print "asdfasdf\r";
print "asdf";
print "\b \b";

print "\n\n";

Note that this will cause problems if with things like tabs, line feeds, et al.
0
 
ddaAuthor Commented:
It works!. Thanks a lot.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now