perlfunc
gods
<P>
select - reset default output or do
<FONT SIZE=-1>I/O</FONT> multiplexing
<P>
<HR>
<P>
select
<FONT SIZE=-1>FILEHANDLE</FONT>
<P>
select
<P>
select
<FONT SIZE=-1>RBITS,WBITS,EBITS,TIMEOUT</FONT>
<P>
<HR>
<P>
Returns the currently selected filehandle. Sets the current default filehandle for output, if
<FONT SIZE=-1>FILEHANDLE</FONT> is supplied. This has two effects: first, a
[perlfunc:write|write()] or a [perlfunc:print|print()] without a filehandle will default to this
<FONT SIZE=-1>FILEHANDLE.</FONT> Second, references to variables related to
output will refer to this output channel. For example, if you have to set
the top of form format for more than one output channel, you might do the
following:
<P>
<PRE> select(REPORT1);
$^ = 'report1_top';
select(REPORT2);
$^ = 'report2_top';
</PRE>
<P>
<FONT SIZE=-1>FILEHANDLE</FONT> may be an expression whose value gives the
name of the actual filehandle. Thus:
<P>
<PRE> $oldfh = select(STDERR); $| = 1; select($oldfh);
</PRE>
<P>
Some programmers may prefer to think of filehandles as objects with
methods, preferring to write the last example as:
<P>
<PRE> use IO::Handle;
STDERR->autoflush(1);
</PRE>
<P>
This calls the
<CODE>select(2)</CODE> system call with
the bit masks specified, which can be constructed using [perlfunc:fileno|fileno()] and [perlfunc:vec|vec()], along these lines:
<P>
<PRE> $rin = $win = $ein = '';
vec($rin,fileno(STDIN),1) = 1;
vec($win,fileno(STDOUT),1) = 1;
$ein = $rin | $win;
</PRE>
<P>
If you want to select on many filehandles you might wish to write a
subroutine:
<P>
<PRE> sub fhbits {
my(@fhlist) = split(' ',$_[0]);
my($bits);
for (@fhlist) {
vec($bits,fileno($_),1) = 1;
}
$bits;
}
$rin = fhbits('STDIN TTY SOCK');
</PRE>
<P>
The usual idiom is:
<P>
<PRE> ($nfound,$timeleft) =
select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
</PRE>
<P>
or to block until something becomes ready just do this
<P>
<PRE> $nfound = select($rout=$rin, $wout=$win, $eout=$ein, undef);
</PRE>
<P>
Most systems do not bother to return anything useful in <CODE>$timeleft</CODE>, so calling
<CODE>select()</CODE> in scalar context
just returns <CODE>$nfound</CODE>.
<P>
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<CODE>$timeleft</CODE>. If not, they always return
<CODE>$timeleft</CODE> equal to the supplied <CODE>$timeout</CODE>.
<P>
You can effect a sleep of 250 milliseconds this way:
<P>
<PRE> select(undef, undef, undef, 0.25);
</PRE>
<P>
<STRONG>WARNING</STRONG>: One should not attempt to mix buffered
<FONT SIZE=-1>I/O</FONT> (like [perlfunc:read|read()]
or
<FONT SIZE=-1><FH>)</FONT> with [perlfunc:select|select()], except as permitted by
<FONT SIZE=-1>POSIX,</FONT> and even then only on
<FONT SIZE=-1>POSIX</FONT> systems. You have to use
[perlfunc:sysread|sysread()] instead.
<HR>