Can you force flush output in Perl?

use IO::Handle;
STDOUT->flush();

There are several ways you can turn on autoflush:

$|++;

at the beginning, or also with a BEGIN block:

BEGIN{ $| = 1; }

However, it seems to be something unusual with your configuration, because usually a \n at the end triggers the flushing (at least of the terminal).


To those who don't want to call flush() following every print like a baby-sitter thing, because it might be in a loop or something and you simply want your print to be unbuffered, then simply put this at the top portion of your perl script:

STDOUT->autoflush(1);

Thereafter, no need to call flush() after print.


By default, STDOUT is line-buffered (flushed by LF) when connected to a terminal, and block-buffered (flushed when buffer becomes full) when connected to something other than a terminal. Furthermore, <STDIN> flushes STDOUT when it's connected to a terminal.

This means

  • STDOUT isn't connected to a terminal,
  • you aren't printing to STDOUT, or
  • STDOUT's been messed with.

print prints to the currently selected handle when no handle is provided, so the following will work no matter which of the above is true:

# Execute after the print.
# Flush the currently selected handle.
# Needs "use IO::Handle;" in older versions of Perl.
select()->flush();

or

# Execute anytime before the <STDIN>.
# Causes the currently selected handle to be flushed immediately and after every print.
$| = 1;