2013-06-24 89 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";