in reply to How to disable buffering ?

Instead of flushing the buffer can't we disable the buffering itself ?

I don't think there is much difference between flushing the buffer with every print or write and disabling the buffering, at least from an external perspective (i.e. without looking at the code that implements the functions). But you may mean something different than what I understand.

You may find PerlIO interesting. You can open a file with the 'unix' layer specified, in which case it is unbuffered, at least on my linux system.

use strict; use warnings; open(my $fh, '>:unix', "test.txt") or die "test.txt: $!"; foreach my $i (1..20) { print $fh "iteration $i\n"; sleep(5); } close($fh);

Perhaps this satisfies your definition of "disable the buffering".

You might also be interested to investigate the setbuf and setvbuf methods of IO::Handle.

Another option is to use syswrite which "bypasses buffered IO".

update: If you are interested in manipulating the I/O stack on a filehandle that is already open, such as STDOUT, you can use binmode (at least you can on linux, I don't know if this would work on all or any other platforms):

use strict; use warnings; use PerlIO; print join(', ', PerlIO::get_layers(*STDOUT)) . "\n"; binmode(*STDOUT, ":pop"); print join(', ', PerlIO::get_layers(*STDOUT)) . "\n"; __END__ unix, perlio unix

After this change, output to STDOUT is unbuffered even if STDOUT is redirected to a file or pipe.

Replies are listed 'Best First'.
Re^2: How to disable buffering ?
by almut (Canon) on Jun 04, 2009 at 03:42 UTC
    You might also be interested to investigate the setbuf and setvbuf methods of IO::Handle.

    Problem with those is that they're usually not available starting with Perl 5.8.0, because they rely on stdio, while newer perls are typically built with perlio...

    $ perl -MIO::Handle -e'IO::Handle->new->setvbuf($buf,1,1024)' IO::Handle::setvbuf not implemented on this architecture at -e line 1.

    (But it's still recommended to read the respective C man page for setvbuf - even if you can't use that functionality from Perl :)  - as it gives a nice introduction to buffering in general, i.e. block-buffered vs. line-buffered vs. unbuffered, etc.)