通过我previous question的讨论,我发现Perl默认提供行缓冲输出。
$| = 0; # for buffered output (by default)
如果要获得无缓冲输出,请将特殊变量$|
设置为1,即
$| = 1; # for unbuffered output
现在我想知道一个人应该选择无缓冲输出的可能情况?
答案 0 :(得分:9)
您希望交互式任务具有无缓冲输出。通过这种方式,我的意思是当你期望别人或别的东西响应输出时你不希望输出卡在某个缓冲区中。
例如,您不希望缓冲发送到STDOUT的用户提示。 (这就是为什么STDOUT在连接到终端时永远不会完全缓冲的原因。它只是行缓冲,缓冲区是通过尝试从STDIN读取来刷新的。)
例如,您希望通过管道和套接字发送的请求不会卡在某个缓冲区中,因为连接的另一端永远不会看到它。
我能想到的唯一另一个原因是,如果发生无法恢复的错误(例如恐慌或信号死亡),您不希望重要数据卡在缓冲区中。
例如,您可能希望保留一个未缓冲的日志文件,以便能够诊断出严重的问题。 (这就是默认情况下STDERR没有缓冲的原因。)
答案 1 :(得分:8)
以下是来自StackOverflow的Perl用户的一小部分示例,他们从学习设置$| = 1
中获益:
STDOUT redirected externally and no output seen at the console
Perl Print function does not work properly when Sleep() is used
can't write to file using print
Perl: Running a "Daemon" and printing
Redirecting STDOUT of a pipe in Perl
Why doesn't my parent process see the child's output until it exits?
Why does adding or removing a newline change the way this perl for loop functions?
In Perl, how do I process input as soon as it arrives, instead of waiting for newline?
Is it possible to print from a perl CGI before the process exits?
Why doesn't print output anything on each iteration of a loop when I use sleep?
答案 2 :(得分:3)
通过套接字或管道写入另一个程序时非常有用。当您将调试信息写入STDOUT以实时观察程序状态时,它也很有用。