2

By the discussion in my previous question I came to know that Perl gives line buffer output by default.

$| = 0; # for buffered output (by default)

If you want to get unbuffered output then set the special variable $| to 1 i.e.

$| = 1;  # for unbuffered output

Now I want to know that what can be the possible situations where one should prefer the unbuffered output?

Community
  • 1
  • 1
Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
  • 2
    Note that setting $| true does NOT make output unbuffered. Output will still be buffered, but the buffer will be flushed more often than if $| was left false. – tadmc Jul 03 '11 at 12:40
  • Oh I see, thank you very much for providing this information tadmc :) – Chankey Pathak Jul 03 '11 at 13:32
  • @tadmc, @Chankey Pathak, Setting `$|` to true *does* make the output unbuffered. All data is sent to the OS before `print` returns. (The OS may do some form of buffering too, but that's something different. Those buffers are flushed using `fsync(2)`.) – ikegami Jul 04 '11 at 18:06

3 Answers3

9

You want unbuffered output for interactive tasks. By that, I mean you don't want output stuck in some buffer when you expect someone or something else to respond to the output.

For example, you wouldn't want user prompts sent to STDOUT to be buffered. (That's why STDOUT is never fully buffered when attached to a terminal. It is only line buffered, and the buffer is flushed by attempts to read from STDIN.)

For example, you'd want requests sent over pipes and sockets to not get stuck in some buffer, as the other end of the connection would never see it.


The only other reason I can think of is when you don't want important data to be stuck in a buffer in the event of a unrecoverable error such as a panic or death by signal.

For example, you might want to keep a log file unbuffered in order to be able to diagnose serious problems. (This is why STDERR isn't buffered by default.)

ikegami
  • 367,544
  • 15
  • 269
  • 518
3

It can be useful when writing to another program over a socket or pipe. It can also be useful when you are writing debugging information to STDOUT to watch the state of your program live.

mfollett
  • 1,814
  • 15
  • 27