Perl user input timeout

I wanted to request user input and after a while, if there is no answer, the script should exit. I had a code for this

eval {
        local $SIG{ALRM} = sub { die "timeout getting the input \n" };
        alarm 5;
        $answer = <STDIN>;
        alarm 0;
        chomp $answer;
    };
    if ($@) {
        #die $@ if $@ ne "timeout getting the input\n";
        $answer = 'A';
    }

The alarm timeout works as expected, but I wanted to get additional print instructions after every second decrement that looked like a countdown (for example, for 10 seconds they say β€œ10 ... 9..8..so on) Can anyone -Never help how to enable this feature along with a timeout.

thank

+4
source share
1 answer
# disable output buffering
$| = 1;

my $answer;
eval {
        my $count = 10;
        local $SIG{ALRM} = sub {
          # print counter and set alaram again
          if (--$count) { print "$count\n"; alarm 1 } 
          # no more waiting
          else { die "timeout getting the input \n" }
        };
        # alarm every second
        alarm 1;
        $answer = <STDIN>;
        alarm 0;
        chomp $answer;
};
if ($@) {
        #die $@ if $@ ne "timeout getting the input\n";
        $answer = 'A';
}
+6
source

Source: https://habr.com/ru/post/1543030/


All Articles