如何在不等待 Perl 输入的情况下获取用户输入? [英] How can I get user input without waiting for enter in Perl?
问题描述
我正在尝试用 Perl 制作一个交互式 shell 脚本.
I am trying to make an interactive shell script in Perl.
我能找到的唯一用户输入如下:
The only user input I can find is the following:
$name = <STDIN>;
print STDOUT "Hello $name\n";
但是在这种情况下,用户必须始终按 Enter 才能使更改生效.按下按钮后如何让程序立即运行?
But in this the user must always press enter for the changes to take effect. How can I get the program to proceed immediately after a button has been pressed?
推荐答案
来自 perlfaq8 的如何在不等待返回键的情况下只读取一个键?:
控制输入缓冲是一个非常依赖于系统的问题.在许多系统上,您可以只使用 perlfunc 中 getc 中所示的 stty 命令,但正如您所见,这已经让您陷入了可移植性障碍.
Controlling input buffering is a remarkably system-dependent matter. On many systems, you can just use the stty command as shown in getc in perlfunc, but as you see, that's already getting you into portability snags.
open(TTY, "+</dev/tty") or die "no tty: $!";
system "stty cbreak </dev/tty >/dev/tty 2>&1";
$key = getc(TTY); # perhaps this works
# OR ELSE
sysread(TTY, $key, 1); # probably this does
system "stty -cbreak </dev/tty >/dev/tty 2>&1";
来自 CPAN 的 Term::ReadKey 模块提供了一个易于使用的界面,它应该比为每个键使用 stty 更有效.它甚至包括对 Windows 的有限支持.
The Term::ReadKey module from CPAN offers an easy-to-use interface that should be more efficient than shelling out to stty for each key. It even includes limited support for Windows.
use Term::ReadKey;
ReadMode('cbreak');
$key = ReadKey(0);
ReadMode('normal');
但是,使用该代码需要您有一个可用的 C 编译器,并且可以使用它来构建和安装 CPAN 模块.这是使用标准 POSIX 模块的解决方案,该模块已在您的系统上(假设您的系统支持 POSIX).
However, using the code requires that you have a working C compiler and can use it to build and install a CPAN module. Here's a solution using the standard POSIX module, which is already on your system (assuming your system supports POSIX).
use HotKey;
$key = readkey();
这是 HotKey 模块,它隐藏了操纵 POSIX termios 结构的有些神秘的调用.
And here's the HotKey module, which hides the somewhat mystifying calls to manipulate the POSIX termios structures.
# HotKey.pm
package HotKey;
@ISA = qw(Exporter);
@EXPORT = qw(cbreak cooked readkey);
use strict;
use POSIX qw(:termios_h);
my ($term, $oterm, $echo, $noecho, $fd_stdin);
$fd_stdin = fileno(STDIN);
$term = POSIX::Termios->new();
$term->getattr($fd_stdin);
$oterm = $term->getlflag();
$echo = ECHO | ECHOK | ICANON;
$noecho = $oterm & ~$echo;
sub cbreak {
$term->setlflag($noecho); # ok, so i don't want echo either
$term->setcc(VTIME, 1);
$term->setattr($fd_stdin, TCSANOW);
}
sub cooked {
$term->setlflag($oterm);
$term->setcc(VTIME, 0);
$term->setattr($fd_stdin, TCSANOW);
}
sub readkey {
my $key = '';
cbreak();
sysread(STDIN, $key, 1);
cooked();
return $key;
}
END { cooked() }
1;
这篇关于如何在不等待 Perl 输入的情况下获取用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!