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

后端 未结 3 1291
一个人的身影
一个人的身影 2020-12-03 14:46

Today in my college a teacher asked me a question. He wrote this code on the paper and said \"What will be the output of this code?\"

use warnings;

for (1          


        
3条回答
  •  难免孤独
    2020-12-03 15:07

    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;
    }
    

提交回复
热议问题