我有一个Perl脚本,要求用户输入一个密码。我们如何只回应“*”代替用户键入的字符?
我正在使用Windows XP / Vista。
解决方法
你可以玩Term :: ReadKey。这里有一个非常简单的例子,有一些检测用于退格键和删除键。我已经在Mac OS X 10.5上进行了测试,但根据
ReadKey manual,它应该在Windows下工作。
manual表示在Windows下使用非阻塞读取(ReadKey(-1))将失败。这就是为什么我使用的是基本上是getc的ReadKey(0)(更多的是在
libc manual中的getc)。
#!/usr/bin/perl
use strict;
use warnings;
use Term::ReadKey;
my $key = 0;
my $password = "";
print "\nPlease input your password: ";
# Start reading the keys
ReadMode(4); #disable the control keys
while(ord($key = ReadKey(0)) != 10)
# This will continue until the Enter key is pressed (decimal value of 10)
{
# For all value of ord($key) see http://www.asciitable.com/
if(ord($key) == 127 || ord($key) == 8) {
# DEL/Backspace was pressed
#1. Remove the last char from the password
chop($password);
#2 move the cursor back by one,print a blank character,move the cursor back by one
print "\b \b";
} elsif(ord($key) < 32) {
# Do nothing with these control characters
} else {
$password = $password.$key;
print "*(".ord($key).")";
}
}
ReadMode(0); #Reset the terminal once we are done
print "\n\nYour super secret password is: $password\n";