- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>


This calls the select(2) syscall with the bit masks specified, which can be constructed using fileno and vec, along these lines:

$rin = $win = $ein = ”;
vec($rin,fileno(STDIN),1) = 1;
vec($win,fileno(STDOUT),1) = 1;
$ein = $rin | $win;

If you want to select on many filehandles, you may wish to write a subroutine like this:

sub fhbits {
    my(@fhlist) = split(' ',$_[0]);
    for (@fhlist) {
        vec($bits,fileno($_),1) = 1;
$rin = fhbits('STDIN TTY SOCK');

The usual idiom is:

($nfound,$timeleft) =
  select($rout=$rin, $wout=$win, $eout=$ein, $timeout);

or to block until something becomes ready just do this

$nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);

Most systems do not bother to return anything useful in $timeleft, so calling select() in scalar context just returns $nfound.

Any of the bit masks can also be undef. The timeout, if specified, is in seconds, which may be fractional. Note: not all implementations are capable of returning the $timeleft. If not, they always return $timeleft equal to the supplied $timeout.

You can effect a sleep of 250 milliseconds this way:

select(undef, undef, undef, 0.25);

Note that whether select gets restarted after signals (say, SIGALRM) is implementation-dependent. See also 28 for notes on the portability of select.

On error, select behaves like select(2): it returns -1 and sets $!.

On some Unixes, select(2) may report a socket file descriptor as "ready for reading" when no data is available, and thus a subsequent read blocks. This can be avoided if you always use O_NONBLOCK on the socket. See select(2) and fcntl(2) for further details.

WARNING: One should not attempt to mix buffered I/O (like read or <FH>) with select, except as permitted by POSIX, and even then only on POSIX systems. You have to use sysread instead.

ISBN 9781906966027Perl Language Reference ManualSee the print edition