我有一个Perl脚本,要求用户输入密码.我怎样才能回复'*'代替用户输入的字符,因为他们输入的字符?
我正在使用Windows XP/Vista.
在过去,我使用了IO :: Prompt.
use IO::Prompt; my $password = prompt('Password:', -e => '*'); print "$password\n";
如果您不想使用任何包...仅适用于UNIX
system('stty','-echo'); chop($password=); system('stty','echo');
您可以使用Term :: ReadKey.这是一个非常简单的示例,有一些检测退格键和删除键.我在Mac OS X 10.5上测试了它,但根据ReadKey手册,它应该在Windows下运行.该手册指出,在Windows下使用非阻塞读(ReadKey(-1)
)会失败.这就是为什么我使用基本上的ReadKey(0)getc
(更多关于libc手册中的 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";
您应该查看Term :: ReadKey或Win32 :: Console.您可以使用这些模块读取单个键击并发出"*"或其他内容.