http://www.perlmonks.org?node_id=63680

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question: (input and output)

I want to capture a single character like the C function getch(). $ch = <STDIN> and $ch = getc() don't return until the user enters a trailing newline. What method(s) are available for this?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I get just one character from STDIN?
by fizbin (Chaplain) on Apr 14, 2003 at 14:50 UTC

    The basic problem is that the terminal device driver doesn't consider a read to have happened until the user presses a return character - this means that no program is going to be able to read a single character unless they first tell the device driver: "Behave differently, and consider a read complete after a single character".

    Hence the suggestion to use Term::ReadKey - it tells the device to behave differently. At a C level, you'd use tcsetattr out of the termios function set. If for some reason you don't think that your deployment environment will have Term::ReadKey installed, you could try a system call to stty; "stty cbreak" will enter the one-character-at-a-time mode and "stty icanon" will take you back. (see stty's man page)

    By the way, on Win32 the way I'd approach this is though the InputChar function inside Win32::Console.

Re: is ther any way to get only one char from stdin
by AgentM (Curate) on Mar 12, 2001 at 02:56 UTC
    use Curses; ...#initialization stuff my $char=getch();
    Read more on Curses in your local man pages for more terminal manipulation goodness.
Re: is ther any way to get only one char from stdin
by crazyinsomniac (Prior) on Mar 12, 2001 at 08:27 UTC
Re: How can I get just one character from STDIN?
by teleron (Novice) on Apr 27, 2001 at 07:52 UTC
    Use Term::ReadKey. Set Readmode 'cbreak'. I use it if I am in a loop and need to get out by pressing a key.
Re: is ther any way to get only one char from stdin
by Caillte (Friar) on Mar 12, 2001 at 06:22 UTC

    Another way is:

    $buf = ' '; while($buf) { sysread STDIN, $buf, 1; print "$buf\n" # or whatever else you want # to do with it ;) }

    I've tested this out on linux and it works fine. Any reason why it wouldnt work on other platforms?

    Editor: The problem with this method is that the sysread will hang until the user presses the RETURN key (so if the user really only enters one character and it isn't RETURN, then the program will just "hang").

Re: is ther any way to get only one char from stdin
by Caillte (Friar) on Mar 12, 2001 at 14:38 UTC

    Well, methinks we have demonstrated TIMTOWTDI quite well today ;)

    Originally posted as a Categorized Answer.