Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Perl use different handles for pipe input and keyboard input?

Tags:

input

pipe

perl

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?

like image 842
Arkady Avatar asked Jan 31 '11 19:01

Arkady


1 Answers

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);
like image 76
DVK Avatar answered Nov 15 '22 08:11

DVK