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

Dearest Monks and Friends, Is there a way to to detect a character typed in STDIN without having pressed the RETURN key...And then take an action if that character is detected. I have a
while(<STDIN>) { }
loop and i can enter input and process the input fine as long as the RETURN key is pressed... but what i'd really like to do is listen for a particular character to be typed at STDIN and then call a subroutine without having pressed the RETURN key at all. for Example I'd like to listen for the character `%` in some text entered at STDIN , say for e.g. `Hello %` and without pressing the RETURN key, call a subroutine since `%` was detected. I'd really, really appreciate any input on this. I'm really new to perl and thus far it has been good learning this amazing language, but i still need some help around the tricky bends, i hope you monks can guide me and show me the path to enlightenment ;).Thanks a lot in advance.

Replies are listed 'Best First'.
Re: Action based on Character recieved from STDIN
by Plankton (Vicar) on Aug 30, 2004 at 21:57 UTC
    Try this ...
    bash-2.05b$ cat readkey.pl #!/usr/bin/perl use Term::ReadKey; ReadMode 4; # Turn off controls keys while (not defined ($key = ReadKey(-1))) {} print "Get key $key\n"; ReadMode 0; # Reset tty mode before exiting bash-2.05b$ ./readkey.pl Get key 7
    You may have to install TermReadKey I installed version 2.14. 2.21 didn't work for me for some reason? I am running Redhat 9 / Perl 5.8.

    Plankton: 1% Evil, 99% Hot Gas.
Re: Action based on Character recieved from STDIN
by Prior Nacre V (Hermit) on Aug 31, 2004 at 10:42 UTC

    Something like this:

    [ ~/tmp ] $ perl -wle 'use strict; { local $/ = \1; while (<>) { print + "Char: ", $., " is ", $_ } }' qwerty Char: 1 is q Char: 2 is w Char: 3 is e Char: 4 is r Char: 5 is t Char: 6 is y Char: 7 is [ ~/tmp ] $

    Update: See this excellent article which discusses the special variables used here.
    Also note that the 'l' in -wle sets $\.

    Regards,

    PN5