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

Hi, Let's say I have a code that keeps printing out some message to STDOUT like below.
#!/usr/bin/perl while(1){ print "Somebody, stop me..\n"; sleep(1); }
Now this program needs to monitor the key event and if 's' key is pressed, it changes the message to, say "somebody, start me". Afterwards, everytime 's' key is pressed, it pingpongs the message. The question is how I can detect the key input while the program is printing out the message in the infinite loop. I read some thread saying ReadKey can do it, but not sure how I can do it in this scenario. Appreciate your suggestion.

Replies are listed 'Best First'.
Re: detecting the keystroke.
by almut (Canon) on Apr 28, 2010 at 06:48 UTC
    I read some thread saying ReadKey can do it, but not sure how I can do it in this scenario.

    You could use non-blocking reads:

    #!/usr/bin/perl use Term::ReadKey; ReadMode 3; # echo off my $msg = "Somebody, stop me.."; while(1){ print "$msg\n"; sleep(1); my $key = ReadKey(-1); # -1 means non-blocking if (defined($key) and $key eq "s") { $msg = "somebody, start me"; } } ReadMode 0;
      Thanks, It's working now.