http://qs1969.pair.com?node_id=484881


in reply to Re^2: About non-blocking sockets
in thread About non-blocking sockets

Blocking is when an action will stall if it can't be completed immediately.
An example using a socket would be if you read from it when there is no data to receive my $line = <$soc>; if there is no data the program will electively wait at this bit of code until a full line of data is received then the read operation will return and the program will continue. The waiting is called blocking. It's most often a concern when reading data, but in some circumstances it can happen when writing as well.
To see blocking in effect try

print "enter some text and press enter\n"; print "enter quit to exit\n"; while (<>) { chomp; exit if $_ = quit"; print "I got $_\n"; }
In the above code the readline operator (<>) will block waiting for a line to be typed in on the console. When enter is pressed it will be read in and printed back out, then it will block again at the readline.

Buffering (controlled by $| or ->autoflush) is when input or output is collected together and stored before it moves from it's source to it's destination.
It can be though of a bit like a bucket, each time you print a cup of water is poured into the bucket. Because for the computer it takes time to empty the bucket it's only emptied when enough water is poured in to fill it up. However if it is important that the water reach it's destination in a timely fashion you can set the bucket to be emptied after each addition of water.
To see buffering try

print "sleeping: "; sleep 2; print "done\n"; sleep 1; $|=1; print "sleeping again: "; sleep 2; print "done\n"
Under most consoles (but possibly not all) you will see nothing for 2 seconds and then the full line "sleeping: done\n" will be printed out. Then a second later you will see "sleeping again: " printed out with the cursor left at the end of the line. Two seconds later "done\n" is printed. The difference is because most consoles are line buffered by default. That means they wait until they have a full line before they print any thing out. Setting $| to a true value causes this buffer to be flushed after each print statement, letting you see a partial line.