How can I prompt a terminal user for a password without showing the password in the terminal? There's a similar question for How can I enter a password using Perl and replace the characters with '*'?, but the answers appear to be out-of-date or broken.
I was looking for answers to this question and wasn't satisfied with the questions on later pages of results that had the answer tangentially to other concerns.
Also, perlfaq8 has an example that is incomplete (oh, and who used to maintain that ;).
use Term::ReadKey;
ReadMode('noecho');
my $password = ReadLine(0);
When you do that without resetting the terminal, nothing else echos! Oops!
I'm also looking for newer answers or modules we can provide to people who want to do this.
To use Term::ReadKey, this works:
sub prompt_for_password {
require Term::ReadKey;
# Tell the terminal not to show the typed chars
Term::ReadKey::ReadMode('noecho');
print "Type in your secret password: ";
my $password = Term::ReadKey::ReadLine(0);
# Rest the terminal to what it was previously doing
Term::ReadKey::ReadMode('restore');
# The one you typed didn't echo!
print "\n";
# get rid of that pesky line ending (and works on Windows)
$password =~ s/\R\z//;
# say "Password was <$password>"; # check what you are doing :)
return $password;
}