2013-06-24 170 views
0

如何才能获得用户输入,直到经过一段时间(毫秒,我正在使用Time::HiRes模块),但如果时间流逝且没有输入,则不会发生任何事情。具体来说,我一直一字一个打印问题,直到STDIN发生中断为止。要做到这一点,程序会在继续打印前等待少量时间,如果没有中断,则打印下一个字。我该怎么做,或者是更好的选择。谢谢一堆。我最初的计划看起来是这样的:直到时间流逝用户输入

use Time::HiRes qw/gettimeofday/; 
$initial_time = gettimeofday(); 
until (gettimeofday() - $a == 200000) { 
     ; 
     if ([<]STDIN[>]) { #ignore the brackets 
       print; 
     } 
} 

+0

一些解决方案:轮询期限:: Readkey,IO ::选择,使得处理无阻塞,通过中断信号 – ikegami

回答

1

看在Time::HiResualarm功能。

它的工作方式与alarm相似,因此请查看如何使用它的示例。

这里有一个完整的例子:

#!/usr/bin/perl 

# Simple "Guess the Letter" game to demonstrate usage of the ualarm function 
# in Time::HiRes 

use Time::HiRes qw/ualarm/; 

my @clues = ("It comes after Q", "It comes before V", "It's not in RATTLE", 
    "It is in SNAKE", "Time's up!"); 
my $correctAnswer = "S"; 

print "Guess the letter:\n"; 

for (my $i=0; $i < @clues; $i++) { 
    my $input; 

    eval { 
     local $SIG{ALRM} = sub { die "alarm\n" }; 
     ualarm 200000; 
     $input = <STDIN>; 
     ualarm 0; 
    }; 

    if ([email protected]) { 
     die unless [email protected] eq "alarm\n"; # propagate unexpected errors 
     # timed out 
    } 
    else { 
     # didn't 
     chomp($input); 
     if ($input eq $correctAnswer) { 
      print "You win!\n"; 
      last; 
     } 
     else { 
      print "Keep guessing!\n"; 
     } 
    } 

    print $clues[$i]."\n"; 
} 

print "Game over man!\n";