perlfaq nodetype
faq_monk
<P>
The
<FONT SIZE=-1>C</FONT> standard
<FONT SIZE=-1>I/O</FONT> library (stdio) normally buffers characters sent to devices. This is done for efficiency reasons, so that there isn't a system call for each byte. Any time you use
<CODE>print()</CODE> or
<CODE>write()</CODE> in Perl, you go though this buffering.
<CODE>syswrite()</CODE> circumvents stdio and buffering.
<P>
In most stdio implementations, the type of output buffering and the size of
the buffer varies according to the type of device. Disk files are block
buffered, often with a buffer size of more than 2k. Pipes and sockets are
often buffered with a buffer size between 1/2 and 2k. Serial devices (e.g.
modems, terminals) are normally line-buffered, and stdio sends the entire
line when it gets the newline.
<P>
Perl does not support truly unbuffered output (except insofar as you can
<U>syswrite(OUT, $char, 1)</U>). What it does instead support is ``command buffering'', in which a
physical write is performed after every output command. This isn't as hard
on your system as unbuffering, but does get the output where you want it
when you want it.
<P>
If you expect characters to get to your device when you print them there, you'll want to autoflush its handle. Use
<CODE>select()</CODE> and the
<CODE>$|</CODE> variable to control autoflushing (see <EM>perlvar/$</EM> and <U>select</U>):
<P>
<PRE> $old_fh = select(OUTPUT_HANDLE);
$| = 1;
select($old_fh);
</PRE>
<P>
Or using the traditional idiom:
<P>
<PRE> select((select(OUTPUT_HANDLE), $| = 1)[0]);
</PRE>
<P>
Or if don't mind slowly loading several thousand lines of module code just
because you're afraid of the <CODE>$|</CODE> variable:
<P>
<PRE> use FileHandle;
open(DEV, "+</dev/tty"); # ceci n'est pas une pipe
DEV->autoflush(1);
</PRE>
<P>
or the newer
<FONT SIZE=-1>IO::*</FONT> modules:
<P>
<PRE> use IO::Handle;
open(DEV, ">/dev/printer"); # but is this?
DEV->autoflush(1);
</PRE>
<P>
or even this:
<P>
<PRE> use IO::Socket; # this one is kinda a pipe?
$sock = IO::Socket::INET->new(PeerAddr => 'www.perl.com',
PeerPort => 'http(80)',
Proto => 'tcp');
die "$!" unless $sock;
</PRE>
<P>
<PRE> $sock->autoflush();
print $sock "GET / HTTP/1.0" . "\015\012" x 2;
$document = join('', <$sock>);
print "DOC IS: $document\n";
</PRE>
<P>
Note the bizarrely hardcoded carriage return and newline in their octal equivalents. This is the
<FONT SIZE=-1>ONLY</FONT> way (currently) to assure a proper flush on all platforms, including Macintosh. That the way things work in network programming: you really should specify the exact bit pattern on the network line terminator. In practice,
<CODE>"\n\n"</CODE> often works, but this is not portable.
<P>
See [perlman:perlfaq9|the perlfaq9 manpage] for other examples of fetching URLs over the web.
<P>