6

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?

Arkady
  • 63
  • 3

1 Answers1

13

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);
Boris Däppen
  • 1,186
  • 7
  • 20
DVK
  • 126,886
  • 32
  • 213
  • 327
  • @Arkady - you are welcome. Please feel free to accept the answer by clicking the checkmark next to it (that'll gain you 2 rep points too) as well as to up-vote the answer (up-arrow next to it) – DVK Jan 31 '11 at 20:11
  • `ReadMode` also takes the terminal as second arguments: `ReadMode('noecho', *TTY);`. I submitted this as an edit, so it should be in the original post soon. – Boris Däppen Jul 21 '18 at 20:01