rsriram has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am writing a Win32 script to accept a user name and password. When the user types the password, the text should not be displayed on the screen. I used Term::ReadKey and wrote a code as follows.

print "User name: "; chop ($name=<STDIN>); if ($name eq "") { die "Invalid user"; }else{ print "Password :"; my $pass = ReadKey(2); }

After entering the username, the cursor is not appearing in the screen and if I hit any key, the program terminates after reporting invalid password. Can anyone tell me how to hide the display of password when typing it on the screen?

Replies are listed 'Best First'.
Re: Suppressing display of text in the screen
by marto (Cardinal) on Aug 29, 2006 at 11:49 UTC
    rsriram.

    Please read perlfaq8.
    A short example:
    #!/usr/bin/perl use strict; use warnings; use Term::ReadKey; print "Enter password: "; ReadMode('noecho'); my $password = ReadLine(0); ReadMode('normal'); print "\nEntered $password";
    Hope this helps

    Martin
Re: Suppressing display of text in the screen
by cdarke (Prior) on Aug 29, 2006 at 12:39 UTC
    The documentation implies that ReadKey does not work on Windows, but it does. However, in the spirit of TMTOWTDI:
    use Win32::Console; $CONSOLE = new Win32::Console (STD_INPUT_HANDLE); print "Enter password: "; # prompt $old_mode = $CONSOLE->Mode(); # get current mode $new_mode = $old_mode ^ ENABLE_ECHO_INPUT; # unset echo $CONSOLE->Mode($new_mode); $new_mode = undef; # loose the new_mode chomp($passwd=<STDIN>); # read password $CONSOLE->Mode($old_mode); # reset console

    Incidently, notice that chomp is safer than chop.
Re: Suppressing display of text in the screen
by GrandFather (Saint) on Aug 29, 2006 at 19:09 UTC

    A note unrelated to your question: In generall don't use chop, use chomp instead.

    chop removes the last character without regard to what it is. chomp removes the input record serperator string ($/) from the end of teh string - whatever that may be set to. Generally it is set to the newline character \n (which is most likely a line feed, or on Mac a carriage return character).


    DWIM is Perl's answer to Gödel
Re: Suppressing display of text in the screen
by wojtyk (Friar) on Aug 29, 2006 at 16:15 UTC