perlfaq nodetype
faq_monk
<P>
The very first thing you should do is look into getting the Term::ReadKey extension from
<FONT SIZE=-1>CPAN.</FONT> It now even has limited support for closed, proprietary (read: not open systems, not
<FONT SIZE=-1>POSIX,</FONT> not Unix, etc) systems.
<P>
You should also check out the Frequently Asked Questions list in comp.unix.* for things like this: the answer is essentially the same. It's very system dependent. Here's one solution that works on
<FONT SIZE=-1>BSD</FONT> systems:
<P>
<PRE> sub key_ready {
my($rin, $nfd);
vec($rin, fileno(STDIN), 1) = 1;
return $nfd = select($rin,undef,undef,0);
}
</PRE>
<P>
If you want to find out how many characters are waiting, there's also the
<FONT SIZE=-1>FIONREAD</FONT> ioctl call to be looked at.
<P>
The <EM>h2ph</EM> tool that comes with Perl tries to convert
<FONT SIZE=-1>C</FONT> include files to Perl code, which can be <U>require</U>d.
<FONT SIZE=-1>FIONREAD</FONT> ends up defined as a function in the <EM>sys/ioctl.ph</EM> file:
<P>
<PRE> require 'sys/ioctl.ph';
</PRE>
<P>
<PRE> $size = pack("L", 0);
ioctl(FH, FIONREAD(), $size) or die "Couldn't call ioctl: $!\n";
$size = unpack("L", $size);
</PRE>
<P>
If <EM>h2ph</EM> wasn't installed or doesn't work for you, you can
<EM>grep</EM> the include files by hand:
<P>
<PRE> % grep FIONREAD /usr/include/*/*
/usr/include/asm/ioctls.h:#define FIONREAD 0x541B
</PRE>
<P>
Or write a small
<FONT SIZE=-1>C</FONT> program using the editor of champions:
<P>
<PRE> % cat > fionread.c
#include <sys/ioctl.h>
main() {
printf("%#08x\n", FIONREAD);
}
^D
% cc -o fionread fionread
% ./fionread
0x4004667f
</PRE>
<P>
And then hard-code it, leaving porting as an exercise to your successor.
<P>
<PRE> $FIONREAD = 0x4004667f; # XXX: opsys dependent
</PRE>
<P>
<PRE> $size = pack("L", 0);
ioctl(FH, $FIONREAD, $size) or die "Couldn't call ioctl: $!\n";
$size = unpack("L", $size);
</PRE>
<P>
<FONT SIZE=-1>FIONREAD</FONT> requires a filehandle connected to a stream,
meaning sockets, pipes, and tty devices work, but <EM>not</EM> files.
<P>