Per la maggior parte dei filehandle potete usare la funzione integrata
getc(), ma essa non funzionerà (facilmente) per il terminale.
Per STDIN, usate il modulo Term::ReadKey da CPAN oppure il codice d'esempio
in perlfunc/getc.
Se il vostro sistema supporta l'interfaccia portabile per la programmazione
del sistema operativo (portable operating system programming
interface: POSIX), potete usare il codice seguente, che come potete
notare oltretutto disattiva l'echo dei caratteri.
#!/usr/bin/perl -w
use strict;
$| = 1;
for (1..4) {
my $preso;
print "premi un tasto: ";
$preso = getone();
print "--> $preso\n";
}
exit;
BEGIN {
use POSIX qw(:termios_h);
my ($term, $oterm, $echo, $noecho, $fd_stdin);
$fd_stdin = fileno(STDIN);
$term = POSIX::Termios->new();
$term->getattr($fd_stdin);
$oterm = $term->getlflag();
$echo = ECHO | ECHOK | ICANON;
$noecho = $oterm & ~$echo;
sub cbreak {
$term->setlflag($noecho);
$term->setcc(VTIME, 1);
$term->setattr($fd_stdin, TCSANOW);
}
sub cooked {
$term->setlflag($oterm);
$term->setcc(VTIME, 0);
$term->setattr($fd_stdin, TCSANOW);
}
sub getone {
my $tasto = '';
cbreak();
sysread(STDIN, $tasto, 1);
cooked();
return $tasto;
}
}
END { cooked() }
Il modulo Term::ReadKey di CPAN potrebbe risultare più semplice
da usare. Versioni recenti includono inoltre il supporto per sistemi specifici.
use Term::ReadKey;
open(TTY, "</dev/tty");
print "Premi un tasto: ";
ReadMode "raw";
$tasto = ReadKey 0, *TTY;
ReadMode "normal";
printf "\nHai premuto %s, il cui numero E<egrave> %03d\n",
$tasto, ord $tasto;
|