7

In c++, there is a functio, getch(), which returns the variable of the key you pressed - like enter would be 13. How could I do this in perl?

1
  • 2
    don't forget to mark answers to this and your other questions. So far you've marked 2 out of a possible 8. stackoverflow.com/faq
    – Andy E
    Commented Jun 7, 2010 at 11:44

2 Answers 2

9

You can use Term::ReadKey.

1
  • Because for the most part Term::ReadKey is problematic under Windows. I've not used it in some years so this situation may have changed. As I understand it, the source was a bit too tightly bound to Unix and POSIX...
    – hsmyers
    Commented Mar 2, 2016 at 6:46
5

in short:

$x = ord(getc);

detailed:

$c = getc(STDIN);
$x = ord($c);

from perldoc -f getc :

"However, it cannot be used by itself to fetch single 
characters without waiting for the user to hit enter. 
For that, try something more like":

   1.  if ($BSD_STYLE) {
   2. system "stty cbreak </dev/tty >/dev/tty 2>&1";
   3. }
   4. else {
   5. system "stty", '-icanon', 'eol', "\001";
   6. }
   7.
   8. $key = getc(STDIN);
   9.
  10. if ($BSD_STYLE) {
  11. system "stty -cbreak </dev/tty >/dev/tty 2>&1";
  12. }
  13. else {
  14. system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL
  15. }
  16. print "\n";
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.