I have a Perl script processing a pipe. At some point, I would like the script to pause and ask for user keyboard input. my $input = <STDIN>;
does not work. It just reads next line from the pipe. How can I make Perl use different handles for pipe input and keyboard input?
If you are on a Unix platform, you can open a filehandle to /dev/tty
(or use IO::Pty
).
A good example of working with tty is in "Testing Whether a Program Is Running Interactively" example here: http://pleac.sourceforge.net/pleac_perl/userinterfaces.html
You should also consider doing password IO via Term::ReadKey
(described in perlfaq8) - I think it may be tied to TTY instead of STDIO but am not sure. If it isn't, use the TTY+Term::ReadKey solution listed at the end of this SO answer by brian d foy.
Here's an example.
It's not the best style (doesn't use 3-arg form of open
, nor uses lexical filehandles) but it should work.
use autodie; # Yay! No "or die '' "
use Term::ReadKey;
open(TTYOUT, ">/dev/tty");
print TTYOUT "Password?: ";
close(TTYOUT);
open(TTY, "</dev/tty");
ReadMode('noecho', *TTY);
$password = ReadLine(0, *TTY);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With