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. |