Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read a key from keyboard without ReadKey module 1

Status
Not open for further replies.

msc0tt

IS-IT--Management
Jun 25, 2002
281
CA
I wish to read a key (other than ENTER) from the keyboard. Is there a way to modify the behaviour of <STDIN> so that it returns each keystroke in the stream, without waiting for ENTER?

Note: we can assume this code will always run on a Linux box.

Note 2: I see that there is a Perl module (Term::Readkey) that can do this. My system does not have this module by default, so I presume others also don't. When developinging, I prefer to write my code as dependency-free as possible. This is why I'm trying to 'reinvent' this wheel.

-with thanks
Mike
 
well... leaving aside the (lack of) merits re wheel re-invention

I used to do this in shell scripts -- on the system I was on the command:

stty raw

gave you character by character

I think, anyway.... It's been a while, it was an stty command anyway.

Mike

Want to get great answers to your Tek-Tips questions? Have a look at faq219-2884

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
Mike is right, 'stty raw' will do it. Here's an example:

system(&quot;stty raw&quot;);
print &quot;Press y or n: &quot;;
$answer = getc(STDIN);
system(&quot;stty cooked&quot;);
 
Thanks Mike/Raider,

Works very well. This has progressed into another issue. The cursor keys feed what appears to be three codes into STDIN; code 27 (ESC) followed by two other codes. Is there a way to pre-check STDIN to see if there are additional characters to be read?

Also, I ultimately wish to suppress the key's output to the screen when it is pressed. I will research stty for the correct switch, but if anyone knows offhand?????
-thanks again.
 
You can try just reading until you get what you want like this:
Code:
system(&quot;stty raw&quot;);
print &quot;Press y or n: &quot;;
do {
    $buffer = getc(STDIN);
    $answer = $answer . $buffer;
} until ($answer =~ m/\w/); # Adjust condition to your liking
system(&quot;stty cooked&quot;);
 
Well!!!!!
Dammed if it doesn't work!! I'm not sure what the &quot;condition&quot; does, but who cares! ;-{)

Thanks, Raider!
 
The line '($answer =~ m/\w/);' is true when the variable $answer contains a word character. Word characters are a-Z and 0-9.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top