我对Perl很新,这是我在这里的第一篇文章,所以要温柔。
我在60秒的倒数计时器中使用实时,并且需要能够每10秒停止一次,然后用户必须输入他们是否想要在每个10的间隔继续倒计时。计时器工作,我只是无法弄清楚如何暂停它让用户输入他们的响应。作为答案的基本答案将非常受欢迎,因为我还不了解很多。谢谢,到目前为止,这是我的代码。
my $countdown = 1*60; #60 seconds
$| = 1; #disable output buffering
my $start_time = time;
my $end_time = $start_time + $countdown;
for (;;) {
my $time = time;
last if ($time >= $end_time);
printf("\r%02d:%02d:%02d",
($end_time - $time) / (1*60),
($end_time - $time) / 60%60,
($end_time - $time) % 60,
);
sleep(1);
}
答案 0 :(得分:2)
在收到用户的回复后更新$end_time
。
while (1) {
$countdown--;
$time = time;
last if ($time >= $end_time);
printf("\r%02d:%02d:%02d",
($end_time - $time) / (1*60),
($end_time - $time) / 60%60,
($end_time - $time) % 60,
);
sleep(1);
if ($countdown%10 == 0) {
print "Continue? ";
$answer = <>;
chomp $answer;
last if $answer ne 'y';
$end_time = time + $countdown;
}
}
答案 1 :(得分:1)
在执行6次的循环中使用10s倒计时。
for my $i (1..6) {
if ($i != 1) {
print "\nContinue? ";
$answer = <>;
chomp $answer;
last if !( $answer eq 'y' || $answer eq 'yes' );
}
countdown(10);
}
countdown
只是您发布的代码。
sub countdown {
my ($length) = @_;
my $start_time = time;
my $end_time = $start_time + $length;
for (;;) {
my $time = time;
last if $time >= $end_time;
printf("\r%02d:%02d:%02d",
($end_time - $time) / (1*60),
($end_time - $time) / 60%60,
($end_time - $time) % 60,
);
sleep(1);
}
}