FAQ 5.1 How do I flush/unbuffer an output filehandle? Why must I do this?
am 29.09.2007 09:03:03 von PerlFAQ ServerThis is an excerpt from the latest version perlfaq5.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .
------------------------------------------------------------ --------
5.1: How do I flush/unbuffer an output filehandle? Why must I do this?
Perl does not support truly unbuffered output (except insofar as you can
"syswrite(OUT, $char, 1)"), although it does support is "command
buffering", in which a physical write is performed after every output
command.
The C standard I/O library (stdio) normally buffers characters sent to
devices so that there isn't a system call for each byte. In most stdio
implementations, the type of output buffering and the size of the buffer
varies according to the type of device. Perl's print() and write()
functions normally buffer output, while syswrite() bypasses buffering
all together.
If you want your output to be sent immediately when you execute print()
or write() (for instance, for some network protocols), you must set the
handle's autoflush flag. This flag is the Perl variable $| and when it
is set to a true value, Perl will flush the handle's buffer after each
print() or write(). Setting $| affects buffering only for the currently
selected default file handle. You choose this handle with the one
argument select() call (see "$|" in perlvar and "select" in perlfunc).
Use select() to choose the desired handle, then set its per-filehandle
variables.
$old_fh = select(OUTPUT_HANDLE);
$| = 1;
select($old_fh);
Some modules offer object-oriented access to handles and their
variables, although they may be overkill if this is the only thing you
do with them. You can use IO::Handle:
use IO::Handle;
open(DEV, ">/dev/printer"); # but is this?
DEV->autoflush(1);
or IO::Socket:
use IO::Socket; # this one is kinda a pipe?
my $sock = IO::Socket::INET->new( 'www.example.com:80' );
$sock->autoflush();
------------------------------------------------------------ --------
The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.
If you'd like to help maintain the perlfaq, see the details in
perlfaq.pod.