查看Time::HiResualarm
中的函数。
它的工作原理与警报类似,因此请查看那里的示例以了解如何使用它。
这是一个完整的例子:
#!/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 ($@) {
die unless $@ 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";