The bug doesn't happen because perl has STDIN line-buffered. Select won't notice STDIN has read data until you press enter. This also means there will always be a newline to read for <STDIN>.
sysread will give you the unbuffered activity you expect but select will not. I think this is where you are mistaken. This means select will still be blocking until you press enter. I was able to get select to trigger on a single character by using tcsetattr to disable line-buffering (aka canonical mode) for the terminal. (code at the end of the post)
edit: Just to be clear about what this implies, this leads me to believe that line-buffering happens at a lower level than the perl interpreter. This answers your rhetorical question:
How can the select system call know that Perl has data waiting to be read in a buffer?
It is my hypothesis that the buffer you speak of happens at the system level and not inside the perl interpreter. Using stdio.h functions like getc and getline, you must read input through the terminal's internal buffer while in canonical mode. The read system call (via perl's sysread) does not use this higher-level terminal line buffer.
I have no idea how this works in windows.
#!/usr/bin/env perl
use warnings;
use strict;
use IO::Select;
use IO::Handle;
use Inline 'C';
my $select = IO::Select->new( \*STDIN );
disable_canon_mode() if @ARGV;
# Experiment by commenting out the above line and giving command-line
# arguments.
while ( 1 ) {
$select->can_read; # block until new input
warn "CAN_READ STDIN\n";
my $in;
if ( @ARGV ) {
sysread STDIN, $in, 1;
print "Char read: $in\n";
}
else {
$in = <STDIN>;
print "Line read: $in\n";
}
}
__END__
__C__
#include <termios.h>
#define STDIN 0
void disable_canon_mode ()
{
struct termios tio;
if ( isatty( STDIN ) == 0 ) { return; }
/* Turn off canonical mode, meaning read one char at a time.
Set timer to 0, to wait forever. Minimum chars is 1. */
tcgetattr( STDIN, &tio );
tio.c_lflag &= ~ICANON;
tio.c_cc[ VTIME ] = 0;
tio.c_cc[ VMIN ] = 1;
tcsetattr( STDIN, TCSANOW, &tio );
}
|