Search code examples
perlbufferingoutput-buffering

What can be the possible situations where one should prefer the unbuffered output?


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?


Solution

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