Página 1 de 1

¿ Cómo hacer un Term::ReadKey ?

NotaPublicado: 2007-12-29 19:59 @874
por creating021
En Perl Cookbook sale un ejemplo de cómo usar Term::ReadKey para saber qué tecla fue usada (leer el STDIN sin tener que esperar el "\n").

Yo sé que usando POSIX y sysread se puede hacer:

Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
use POSIX;
use 5.10.0;

my $termios = new POSIX::Termios;
$termios->setcc( VTIME, 1 );
my $key;
sysread ( STDIN, $key, 1 );
say $key;
$termios->setcc( VTIME, 0 );
Coloreado en 0.002 segundos, usando GeSHi 1.0.8.4


Si a este código se le pone las funciones de noecho y echo, está hecho, pero...

¿Qué pasa si quiero leer las flechas ( up, down, right, left ) y otras teclas ( backspace, tab, F1, F2... ) ?

¿Se puede hace con POSIX o tiene que hacerse con Term::ReadKey?

NotaPublicado: 2007-12-29 22:20 @972
por explorer
Encontré esta página donde hay una solución: usar IO::Select para leer el estado del STDIN.

http://www.thescripts.com/forum/thread49817.html

Lo que no me creo es que no exista un módulo para eso. ¿Has mirado perlfaq8? Hay un par de respuestas interesantes.

NotaPublicado: 2007-12-30 10:45 @490
por creating021
Muchas gracias por la respuesta, ahora veo el link y el FAQ

NotaPublicado: 2007-12-31 16:49 @742
por creating021
Al final, esta es la solución:
Sintáxis: [ Descargar ] [ Ocultar ]
Using perl Syntax Highlighting
use POSIX;
use 5.10.0;
use strict;

my $t = new POSIX::Termios;
$t->setcc( VTIME, 1 );
my $att = $t->getattr( fileno(STDIN) );
my $flag = $t->getlflag();
$t->setlflag( $flag & ~&POSIX::ECHO );
$t->setattr( fileno(STDIN), TCSANOW );
my $k;
binmode STDIN;
sysread ( STDIN, $k, 5 );
say ( join " ", ( unpack "c*", $k ) );
if ( $k eq "\e[A" ) { say "up"; }
$t->setlflag(&POSIX::ECHO);
$t->setattr( fileno(STDIN), TCSANOW );
$t->setcc( VTIME, 0 );
 
Coloreado en 0.001 segundos, usando GeSHi 1.0.8.4


Leo 5 bytes y no 1 ya que teclas como F13 ( en darwin ) usa 5 bytes, las teclas up, down, left y right usan 3 bytes, así que 5 bytes el el máximo usado.