冲洗Perl STDIN缓冲区 [英] Flushing Perl STDIN buffer

查看:79
本文介绍了冲洗Perl STDIN缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以清除Perl中的STDIN缓冲区?我程序的一部分输出很长(足以让某人输入几个字符的时间),在该输出之后,我要求输入,但是如果在输出过程中输入了字符,则它们会固定在输入中输入的内容上部分。这是我的问题的一个示例:

Is there any way to clear the STDIN buffer in Perl? A part of my program has lengthy output (enough time for someone to enter a few characters) and after that output I ask for input, but if characters were entered during the output, they are "tacked on" to whatever is entered at the input part. Here is an example of my problem:

for(my $n = 0; $n < 70000; $n++){
   print $n . "\n";
}
chomp(my $input = <STDIN>);
print $input . "\n";

输出将包括在for循环的输出期间输入的所有字符。如何禁用STDIN或刷新STDIN缓冲区(或通过其他任何方式在调用STDIN之前不允许在其中插入额外字符)?

The output would include any characters entered during the output from that for loop. How could I either disable STDIN or flush the STDIN buffer (or any other way to not allow extra characters to be inserted into STDIN before calling it)?

推荐答案

您似乎可以使用 Term完成此操作:: ReadKey 模块:

It looks like you can accomplish this with the Term::ReadKey module:

#!perl

use strict;
use warnings;
use 5.010;

use Term::ReadKey;

say "I'm starting to sleep...";
ReadMode 2;
sleep(10);
ReadMode 3;
my $key;
while( defined( $key = ReadKey(-1) ) ) {}
ReadMode 0;
say "Enter something:";
chomp( my $input = <STDIN> );
say "You entered '$input'";

发生的事情是这样的:


  • ReadMode 2 的意思是将输入模式置于常规模式但关闭回显。这意味着在您使用昂贵的代码时,用户进行的任何键盘敲打都不会在屏幕上产生回响。虽然它仍然会进入 STDIN 的缓冲区,所以...

  • ReadMode 3 STDIN 转换为cbreak模式,这意味着 STDIN 会在每次按键后刷新。这就是为什么...

  • while(defined($ key = ReadKey(-1))){} 发生的原因。这将清除用户在计算昂贵的代码期间输入的字符。然后...

  • ReadMode 0 重置 STDIN ,您可以读取从 STDIN 发出,好像用户没有敲键盘一样。

  • ReadMode 2 means "put the input mode into regular mode but turn off echo". This means that any keyboard banging that the user does while you're in your computationally-expensive code won't get echoed to the screen. It still gets entered into STDIN's buffer though, so...
  • ReadMode 3 turns STDIN into cbreak mode, meaning STDIN kind of gets flushed after every keypress. That's why...
  • while(defined($key = ReadKey(-1))) {} happens. This is flushing out the characters that the user entered during the computationally-expensive code. Then...
  • ReadMode 0 resets STDIN, and you can read from STDIN as if the user hadn't banged on the keyboard.

当我运行此代码并在 sleep(10)期间在键盘上敲击时,然后在提示后输入一些其他文本,它只会打印出我在提示后键入的文本出现。

When I run this code and bang on the keyboard during the sleep(10), then enter some other text after the prompt, it only prints out the text I typed after the prompt appeared.

严格来说,不需要 ReadMode 2 ,但是我把它放在那里,所以屏幕不需要当用户敲击键盘时,文本会变得混乱。

Strictly speaking the ReadMode 2 isn't needed, but I put it there so the screen doesn't get cluttered up with text when the user bangs on the keyboard.

这篇关于冲洗Perl STDIN缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆