How can I print text immediately without waiting for a newline in Perl?

我怕爱的太早我们不能终老 提交于 2020-01-01 07:57:06

问题


I have a computationally expensive task in perl, and would like to inform the user that computation is ongoing by printing out a period after each portion of the computation is completed. Unfortunately, until I print a "\n", none of my periods are printed. How can I address this?


回答1:


You need to set autoflush for STDOUT. Example:

use IO::Handle;
STDOUT->autoflush(1);
foreach (1..20) {
  print '.';
  sleep(1);
}



回答2:


set $|=1 before you start printing. Eg.

perl -e ' $|=1; foreach (1..10) { print "$_ "; sleep(1); }'



回答3:


An excellent article you should read: Suffering from Buffering?




回答4:


See the FAQ How do I flush/unbuffer an output filehandle? Why must I do this? and note:

Besides the $| special variable, you can use binmode to give your filehandle a :unix layer, which is unbuffered ...

For the general problem, you might want to look at Time::Progress:

%b

%B

progress bar which looks like:

##############......................



回答5:


What worked for me was to put the line

STDOUT->autoflush(1);

before my line

print ".";

inside my existing loop. Didn't use the sleep for fear of slowing the things down even more.



来源:https://stackoverflow.com/questions/2434363/how-can-i-print-text-immediately-without-waiting-for-a-newline-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!