

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.




func prompt_yn {
    static rk = frequire('Term::ReadKey');
    rk.ReadMode(4);     # change to raw input mode
 
    var key = '';
    while (key !~ /[yn]/i) {
        while (rk.ReadKey(-1) != nil) {};   # discard any previous input
        print "Type Y/N: ";
        say (key = rk.ReadKey(0));          # read a single character
    }
 
    rk.ReadMode(0);     # reset the terminal to normal mode
    return key.uc;
}
 
var key = prompt_yn();
say "You typed: #{key}";