0

我对 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);
}
4

2 回答 2

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;
    }
}
于 2013-11-01T17:45:42.573 回答
1

在执行 6 次的循环中使用 10 秒倒计时。

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);
    }
}
于 2013-11-01T20:18:01.467 回答