为什么这个perl程序没有打印出来?

时间:2013-04-14 09:36:24

标签: perl unix io terminal stdin

#!/usr/bin/env perl

use Term::ReadKey;
ReadMode 4;
END {
    ReadMode 0; # Reset tty mode before exiting
}

while (<>) {
    $key = ReadKey(0);
    $key == "\x04" and last; # Ctrl+D breaks the loop 
    print $key;
}

当我没有while循环的时候,它打印回来我输入的内容。

它最终甚至不会产生任何输出(如果它正在缓冲它或其他东西)。就像我运行它并键入几个字母并按Ctrl + D.它什么都不打印。

trying to make a program to convert mouse scroll escape codes into keypresses。我希望我不会咆哮错误的树。

2 个答案:

答案 0 :(得分:3)

只需将while条件替换为:

while(1) {
   # ...
}

答案 1 :(得分:3)

这一行

while (<>) 

STDIN读取一行(假设您运行的程序没有命令行参数)。一旦读取了一行,它就会进入while循环体。无论您输入的是什么,包括换行,现在都在$_

现在,您按一个键,它存储在$key中,并在数字上与 CTRL-D 进行比较。由于两者都不是数字,它们最终都为零,循环终止。

这就是为什么你应该打开warnings本来会告诉你的原因:

Argument "^D" isn't numeric in numeric eq (==) at ./tt.pl line 15,  line 1.
Argument "c" isn't numeric in numeric eq (==) at ./tt.pl line 15,  line 1.

当然,将循环终止条件放在它所属的位置是有意义的:

#!/usr/bin/env perl

use strict;
use warnings;

use Term::ReadKey;
ReadMode 4;
END {
    ReadMode 0; # Reset tty mode before exiting
}

my $input;
{
    local $| = 1;
    while ((my $key = ReadKey(0)) ne "\x04") {
        print $key;
        $input .= $key;
    }
}

print "'$input'\n";