如何使用Perl输入密码,并用'*'替换字符? [英] How can I enter a password using Perl and replace the characters with '*'?
问题描述
我有一个Perl脚本,要求用户输入密码.在用户键入字符时,我该如何仅回声"*"?
I have a Perl script that requires the user to enter a password. How can I echo only '*' in place of the character that the user types, as they type it?
我正在使用Windows XP/Vista.
I'm using Windows XP/Vista.
推荐答案
您可以使用Term :: ReadKey玩.这是一个非常简单的示例,其中对退格键和删除键进行了一些检测.我已经在Mac OS X 10.5上对其进行了测试,但是根据 ReadKey手册,它应该在Windows下工作. 手册表示在Windows下使用非阻塞读取(ReadKey(-1)
)将失败.这就是为什么我使用基本上是getc
的ReadKey(0)的原因(有关 libc手册).
You can play with Term::ReadKey. Here is a very simple example, with some detection for backspace and delete key. I've tested it on Mac OS X 10.5 but according to the ReadKey manual it should work under Windows. The manual indicates that under Windows using non-blocking reads (ReadKey(-1)
) will fail. That's why I'm using ReadKey(0) who's basically getc
(more on getc in the libc manual).
#!/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";
这篇关于如何使用Perl输入密码,并用'*'替换字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!