

Task

Obtain a valid   Y   or   N   response from the keyboard.

The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated.

The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need to press an   enter   key.




use Term::ReadKey;
 
ReadMode 4; # change to raw input mode
 
my $key = '';
 
while($key !~ /(Y|N)/i) {
    1 while defined ReadKey -1; # discard any previous input
    print "Type Y/N: ";
    $key = ReadKey 0; # read a single character
    print "$key\n";
}
 
ReadMode 0; # reset the terminal to normal mode
 
print "\nYou typed: $key\n";
 