How to pause real time in Perl

前端 未结 2 1301
旧时难觅i
旧时难觅i 2021-01-16 22:08

I am quite new to Perl and this is my first post here so be gentle.

I am using real time in a countdown timer of 60 seconds and need to be able to stop it every 10 s

相关标签:
2条回答
  • 2021-01-16 22:48

    Update $end_time after getting the response from the user.

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-16 23:05

    Use a 10s countdown in a loop executed 6 times.

    for my $i (1..6) {
        if ($i != 1) {
            print "\nContinue? ";
            $answer = <>;
            chomp $answer;
            last if !( $answer eq 'y' || $answer eq 'yes' );
        }
    
        countdown(10);
    }
    

    Where countdown is simply the code you posted.

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题