austin43 has asked for the wisdom of the Perl Monks concerning the following question:

Greetings monks. I have a problem with using Term::ReadKey. It is working great overall and accepting keypresses, but I don't want the user to be able to accidentally hold down the key and run the subroutine more than once by accident.
use Term::ReadKey; ReadMode(4); my $input = lc(ReadKey(0)); if ($input =~ m/r/) { &subroutine1; } ReadMode(0); exit;
Currently, if you hold down 'r', it will call &subroutine1 multiple times. Is there a way to make the keys only read once when held down? Thanks in advance.

Replies are listed 'Best First'.
Re: ReadKey only read once?
by SuicideJunkie (Vicar) on Mar 31, 2011 at 18:09 UTC

    A very simple way to do it is to save the previous value and/or timestamp, and ignore any key that is identical to the previous if it occurs too soon.

Re: ReadKey only read once?
by ambrus (Abbot) on Mar 31, 2011 at 19:35 UTC

    Change your design then. Require the user to press two keys then, such as "r" and then enter, or "r" and then "y". Either you run the action immediately after the first key but only after you read the second key you get back to the main menu and accept new commands, or you run the action only after the second keystroke.

Re: ReadKey only read once?
by wind (Priest) on Mar 31, 2011 at 18:06 UTC

    You could add a timeout before the subroutine can be run again. However, don't know of a way to modify the basic functionality of a keyboard like this. If it was JavaScript, I would say look for onKeyPress.

    This is of course one reason to use <STDIN> and wait for a return before processing the input

      Thanks for the speedy reply. Sitting here thinking about it I figured it out! The subroutines only need to be run once, and a text file tells the program if that individual subroutine has run before. So if I make it so a variable changes if it has run before, then no reason to let it run again.