Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Ghosted input

by monoxide (Beadle)
on Jun 15, 2007 at 03:54 UTC ( [id://621395]=perlquestion: print w/replies, xml ) Need Help??

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

I want to make a ghosted input for a password in one of my programs. Fiddling around with some sample code from the getc() manual, I finally came up with this:
#!/usr/bin/perl $BSD_STYLE = 1; if ($BSD_STYLE) { system "stty cbreak </dev/tty >/dev/tty 2>&1"; } else { system "stty", '-icanon', 'eol', "\001"; } my $in = ''; while (($key = getc(STDIN)) ne "\n") { $in .= $key; print "\x08 \x08"; } if ($BSD_STYLE) { system "stty -cbreak </dev/tty >/dev/tty 2>&1"; } else { system "stty", 'icanon', 'eol', '^@'; # ASCII null } print "$in\n";
This seems to work perfectly, BUT. Is there an easier/better way of doing this? Failing that, does anyone have any ideas on how to detect whether $BSD_STYLE should be set or not? I was thinking maybe running stty with some parameters and checking the output for some sort of signatures, but this seems to me to be a "bad" solution.

Replies are listed 'Best First'.
Re: Ghosted input
by naikonta (Curate) on Jun 15, 2007 at 04:14 UTC
    Well, If you don't mind to use a module :)
    use strict; use warnings; use Term::ReadKey; my $hint = "I'm not going to tell you! You knew it already"; print "Username: "; chomp(my $user = <STDIN>); # validate $user print "Password: "; ReadMode 'noecho'; chomp(my $pass = <STDIN>); ReadMode 'normal'; # validate $pass print "\nYou said: username=$user, password=($hint)\n";

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

      Aha! This is exactly what I'm looking for thankyou. I don't mind using a module, and I tried a quick search of CPAN, but couldn't find anything.

      monoxide
Re: Ghosted input
by tirwhan (Abbot) on Jun 15, 2007 at 08:04 UTC

    The easiest way I know is using IO::Prompt

    use IO::Prompt; my $passwd = prompt("Enter password: ", -e => ""); print $passwd;

    Note: IO::Prompt autochomps the input for you, so no need to do that manually. Similarly, the popular method of printing a star for each typed character:

    use IO::Prompt; my $passwd = prompt("Enter password: ", -e => "*"); print $passwd;

    All dogma is stupid.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://621395]
Approved by naikonta
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-04-18 06:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found