13 January 2014

Autoflush for Hot Handles in Perl.

Topics: Perl

By default Perl buffers writes to your file handles, most of the time this gives us a performance advantage. Sometimes it is a real headache like when we’re writing tests and want to test our application’s logging. Also if our program dies traumatically the last event may not get written or the buffer completely fails to flush.

The traditional ugly way of dealing with this was to write something like this.

{  my $ofh = select LOG; $| = 1; select $ofh; }

If you do a web search on perl hot handles most of what you’ll find suggests this or using a module like IO:Handle.

Except that there is a much cleaner way of doing it: autoflush, that goes back to at least Perl 5.005, which I just came across in the Perl Documentation as I was revisiting the $ issue one more time.

open( my $FileHandle, '>', $filename ); autoflush $FileHandle 1;

There is still no method I’ve discovered to selectively flush a file handle on demand. I’m using Log::Fast for logging and passing it a FileHandle so all I had to do was use an if statement to make the file hot before creating the logger when debugging.

Using either FileHandle or IO::Handle will get you some other features, the most relevant being to make autoflush a method, but if all you wanted was autoflush, you don’t need them.

Update 2022, in recent Perls IO::File is loaded by open and all you need in your code is $FileHandle->autoflush(1); .