如果没有在终端中显示密码,Perl如何提示输入密码?

bri*_*foy 12 passwords terminal perl

如何在不显示终端密码的情况下提示终端用户输入密码?有一个类似的问题我如何使用Perl输入密码并用'*'替换字符?,但答案似乎已过时或破裂.

我正在寻找这个问题的答案,并且不满意后来的结果页面上的问题,这些问题的答案与其他问题相关.

此外,perlfaq8有一个不完整的例子(哦,谁曾经保持这个;).

 use Term::ReadKey;
 ReadMode('noecho');
 my $password = ReadLine(0);
Run Code Online (Sandbox Code Playgroud)

当你这样做而不重置终端,没有别的回声!哎呀!

我也在寻找能够为想要这样做的人提供更新的答案或模块.

bri*_*foy 10

要使用Term :: ReadKey,这适用于:

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;
}
Run Code Online (Sandbox Code Playgroud)