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 perlvar/$| and perlfunc/select).

Use select() to choose the desired handle, then set its per-filehandle variables.

    $old_fh = select(OUTPUT_HANDLE);
    $| = 1;
    select($old_fh);
Some idioms can handle this in a single statement:

    select((select(OUTPUT_HANDLE), $| = 1)[0]);
    $| = 1, select $_ for select OUTPUT_HANDLE;
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();

Back to perlfaq5