Pic has asked for the wisdom of the Perl Monks concerning the following question:

I'm working on my very first curses app, and now that I've decided to let the user move the cursor around with the arrow keys I've run into my first real roadblock.

I've got a main loop that runs like so:
while ( my $in = $main->getch () ) { # Do stuff here. }
Inside this loop, I'm trying to see if the user presses one of the arrow keys, and from the ncurses tutorial I've been reading (which is for C), it looks like the way to do it is either $in == KEY_LEFT or $in eq KEY_LEFT in the case of the left arrow key. However, this gracefully completely fails to work.

From my efforts at debugging, it looks like the program reads three characters each time one of the arrow keys is pressed.

Does anyone know how I can get this working the way I want to?

Replies are listed 'Best First'.
Re: Arrow keys with Curses.pm
by caelifer (Scribe) on Oct 13, 2006 at 01:15 UTC
    You should call keypad(1) so you can compare returned key code to exported constants.
    use strict; use Curses; my $screen = Curses->new(); # Enable keypad functionality keypad(1); while (my $key = getch()) { do { printw("KEY_LEFT\n"); refresh(); next } if $key eq KEY_L +EFT; do { printw("KEY_RIGHT\n"); refresh(); next } if $key eq KEY_R +IGHT; last; } exit 0;
    BR
      D'oh. That's it of course.

      Now that you've said it I can even see where it's mentioned in the C language tutorial.

      Thanks a lot for your help.
Re: Arrow keys with Curses.pm
by doowah2004 (Monk) on Oct 12, 2006 at 21:33 UTC
    I know this is not exactly what you want, but you may want to look at Curses::Simp I think that it takes out a lot of the guess work. Be warned that I have looked at it but never used it so I can not comment on how well it works.

    Good luck.
Re: Arrow keys with Curses.pm
by sgifford (Prior) on Oct 12, 2006 at 22:20 UTC
    A first step would be to see what character getch is returning, and what's in KEY_LEFT. ord is useful for converting a nonprintable character to a number; you can use length to see if they're multi-character strings.