Perl Term::ReadKey 带箭头键

标签 perl console.readkey readkey

我在 ReadMode('cbreak') 中使用 Term::ReadKey 读取单个字符并根据输入执行操作。这适用于除箭头键之外的所有其他键。当按下箭头键时,该操作执行 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

最佳答案

这是我的工作解决方案......

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;
    }
}

关于Perl Term::ReadKey 带箭头键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32489924/

相关文章:

C++ 如何在 Linux 和 Windows 上不等待按键 grip "Enter"来读取按键

java - java/clojure 中的单字符控制台输入

r - 如何在 R 中等待按键?

javascript - 如何根据点击的链接更改点击事件的结果

regex - 最新的 Perl 不会匹配某些长度超过 32768 个字符的正则表达式

json - 如何使用 perl 读取 https JSON 流?

c++ - Pascal 的 readkey 有等价物吗?在 C 或 C++ 中?

java - java中的Readkey() : how to do it?

html - 如何在 Perl 中从 HTML 中提取 URL 和链接文本?