Main Content

Keyboard reading in Perl - character by character not line by line

Archive - Originally posted on "The Horse's Mouth" - 2009-06-01 09:32:50 - Graham Ellis

If I'm typing in my age in response to a prompt and I start with a "6" character, will you assume that I'm between 60 and 69 years old? You might ... but then I may backspace (having accidentally struck the "6" key and start with a slightly lower digit. But in my program, I do NOT want to have to write my own code to deal with user inputs / errors of this type, and that is why most programming languages read up to and including a new line (a "commit") after which they return just the "cooked" or cleaned up string to the user.

With Perl, "you can do anything" ... you may have heard that said before ... so it is possible to read character by character, using the underlying C language libraries "ioctl" and "fcntl". Which makes it operating system dependent. We have an example here ... and you'll find other examples of clever uses of Perl's IO on that page too, such as turning off echo for password entry, giving the user just a limited time to reply to a prompt, and checking whether or not an input is available before proceeding, rather than locking in a wait state for the keyboard.