Why doesn't print output anything on each iteration of a loop when I use sleep?

我与影子孤独终老i 提交于 2019-11-27 14:41:34

The real issue has nothing to do with sleep, but rather that............

You are Suffering from Buffering. The link provided takes you to an excellent article from The Perl Journal circa 1998 from Marc Jason Dominus (the author of Higher-Order Perl). The article may be over a decade old, but the topic is as relevant today as it was when he wrote it.

Others have explained the $| = 1; technique. I would add to those comments that in the predominant thinking of the Perl community seems to be that $| = 1 is preferable over $|++ simply because it is clearer in its meaning. I know, autoincrement is pretty simple too, but does everyone who will ever look at your code know $|'s behavior when ++ or -- are applied (without looking it up in perlvar). I happen to also prefer to localize any modification of Perl's "special variables" so that the effects are not washing over into other portions of code that may not play nice with a particular change to default Perl behavior. So that being the case, I would write it as:

use strict;
use warnings;

{
    local $| = 1;
    for ( 1 .. 20 ) {
        print '.';
        sleep 1;
    }
}
geekosaur

Perl, and many other programs, line-buffer output by default. You can set $| to 1 if you need unbuffered output.

It's not clearing the buffer. If there is a newline at the end of the print statement it will do that for you automatically:

use warnings;

for (1 .. 20) {
    print ".\n";
    sleep 1;
}

If you don't want the newline (I don't imagine you do) you can use the special autoflush variable $|. Try setting it to 1 or incrementing it.

use warnings;

$|++;

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