Re: How to read from keyboard?



Okay i have the exact answer for you now. The following script will give you decimal and hexidecimal values for each keypress. The hex value can be used in normal regex and print statements using \x; the example in the script quits using capital Q and (from my keyboard) PgUp (this probably remains the same).

Some keys like PgUp and Home give three sets of values per press (except on quit, when you get the wrong two); the one that worked for me was the last one.

nb. make sure you exit this cleanly (capital Q or, if it works, PgUp) because the last line is needed to reset the terminal properly.

#!/usr/bin/perl
# get ASCII values for keypresses

use warnings;
use Term::ReadKey;

ReadMode('cbreak');
print "Press a key.\n";

while (1) { #infinite loop
$C = ReadKey(0);
last if ($C eq "Q");
last unless defined $C;
last if ($C =~ /\x7e/); # eg. \x in regex
printf("$C\tDecimal: %d\tHex: %x\n", ord($C), ord($C));
}

ReadMode('normal'); # IMPORTANT!

Now you should be able to make any key do anything easily.
.



Relevant Pages

  • Re: Detecting keypress when window isnt in focus
    ... the loop with a keypress. ... I can do this with the script below and it ... will let other apps run, by working at the window manager level. ...
    (comp.lang.perl.misc)
  • Detecting keypress when window isnt in focus
    ... the loop with a keypress. ... I can do this with the script below and it ... recognised and the loop doesn't end. ... my $char = ReadKey; ...
    (comp.lang.perl.misc)
  • Re: Disabling/Enabling Keys in BASH Script
    ... > sending a SIGINT upon a specific keypress, and have the shell ... > perform a specific action upon that signal reception. ... CTRL+G but what my problem is while running the script if I didn't press this ...
    (comp.unix.shell)