perl - Why doesn't print output anything on each iteration of a loop when I use sleep? -
today in college teacher asked me question. wrote code on paper , said "what output of code?"
use warnings; (1 .. 20) { print "."; }
i found easy , said loop 20 times , @ each iteration print dot (.) , hence total 20 dots output.
he said right , made changes in code. code was:
use warnings; (1 .. 20) { print "."; sleep 1; }
he said output now? didn't know sleep function, guessed @ each iteration print dot (.) , wait 1 second (because of sleep function) , again iterate , again print (.) wait 1 second , on...
the teacher told me check @ home. tried @ home , came know second code waits 20 seconds , prints dots (20 dots) @ once. want know how happened? why isn't dot (.) getting print on each iteration?
the real issue has nothing sleep
, rather that............
you suffering buffering. link provided takes excellent article perl journal circa 1998 marc jason dominus (the author of higher-order perl). article may on decade old, topic relevant today when wrote it.
others have explained $| = 1;
technique. add comments in predominant thinking of perl community seems $| = 1
preferable on $|++
because clearer in meaning. know, autoincrement pretty simple too, ever @ code know $|
's behavior when ++
or --
applied (without looking in perlvar). happen prefer localize modification of perl's "special variables" effects not washing on other portions of code may not play nice particular change default perl behavior. being case, write as:
use strict; use warnings; { local $| = 1; ( 1 .. 20 ) { print '.'; sleep 1; } }
Comments
Post a Comment