我在ReadMode中使用术语::ReadKey(‘cbreak’)来读取单个字符并根据输入执行操作。这对除箭头键以外的所有其他键都很好。当按下箭头键时,动作执行3次,我理解这是因为箭头键转换为'^[[A',等等].
如何将箭头键转换为ReadKey可以解释的任意单个值?
我尝试了以下代码,但它不起作用:
use Term::ReadKey;
ReadMode('cbreak');
my $keystroke = '';
while ($keystroke ne 'h') {
print "Enter key: ";
#Read user keystroke
$keystroke = ReadKey(0);
chomp($keystroke);
if(ord($keystroke) == 27) {
$keystroke = ('0');
}
}下面是我根据建议编写的代码:
use Term::RawInput;
use strict;
use warnings;
my $keystroke = '';
my $special = '';
while(lc($keystroke) ne 'i' && lc($keystroke) ne 't'){
my $promptp = "Enter key: ";
($keystroke,$special) = rawInput($promptp, 1);
if ($keystroke ne '') {
print "You hit the normal '$keystroke' key\n";
} else {
print "You hit the special '$special' key\n";
}
chomp($keystroke);
$keystroke = lc($keystroke);
}
if($keystroke eq 'i') {
#Do something
}
if($keystroke eq 't') {
#Do something
}现在,不管我按什么,我都不能退出这个循环
这是输出:
Enter key:
Enter key:
Enter key: You hit the normal 't' key
#Proceeds to function发布于 2015-09-11 00:03:24
这是我的解决方案..。
use Term::ReadKey;
ReadMode('cbreak');
{
#Temporarily turn off warnings so no messages appear for uninitialized $keystroke
#that for some reason appears for the if statement
no warnings;
my $keystroke = '';
while ($keystroke ne 'h') {
print "\nEnter key: ";
#Read user keystroke
$keystroke = ReadKey(0);
#The first character for the arrow keys (ex. '^[[A') evaluates to 27 so I check for
#that
if(ord($keystroke) == 27) {
#Flush the rest of the characters from input buffer
#This produces an 'Use of uninitialized value...' error
#for the other two characters, hence 'no warnings' at the beginning.
#This will ignore the other 2 characters and only cause a single iteration
while( defined ReadKey(-1) ) {}
}
ReadMode 0;
}
}发布于 2015-09-09 22:46:06
Term::RawInput没有涵盖所有内容,但对于这项任务来说,这是一个很好的开端:
use Term::RawInput;
my ($keystroke,$special) = rawInput("", 1);
if ($keystroke ne '') {
print "You hit the normal '$keystroke' key\n";
} else {
print "You hit the special '$special' key\n";
}发布于 2015-09-10 09:23:40
如果你想阅读“按键”的高级语义,而不是低级的“终端字节”,你就需要一些东西来解析和收集那些多字节的序列。
对于这类任务,我编写了任期:TermKey
use Term::TermKey;
my $tk = Term::TermKey->new( \*STDIN );
print "Press any key\n";
$tk->waitkey( my $key );
print "You pressed: " . $tk->format_key( $key, 0 );https://stackoverflow.com/questions/32489924
复制相似问题