Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: What the heck does $|++; do?

by crabbdean (Pilgrim)
on Apr 13, 2004 at 19:26 UTC ( [id://344830]=note: print w/replies, xml ) Need Help??


in reply to What the heck does $|++; do?

You've already got lots of good comments here but there is a little more to discuss on this topic to fully flesh it out. There are couple ways to flush buffering.

$old_fh = select(OUTPUT_HANDLE); $| = 1; select($old_fh);
The 'select' statement above selects OUTPUT_HANDLE as the place to 'print' or 'write' their output and returns the name of the old file_handle that previously was recieving the printed output. You can then set the OUTPUT_HANDLE to be unbuffered and use the returned old handle to later to reset your old file handle as the receiver of output. If you wanted to do the same in a little more bizarre way you could write:
select((select(STDERR), $| = 1)[0])
Alternatively you can use the IO:Handle module:
use IO::Handle; OUTPUT_HANDLE->autoflush(1);
Or even again alternatively:
use FileHandle; STDOUT->autoflush(1);
OORRR even again for linguistic nice-ness:
use IO::Handle; autoflush ONE_HANDLE 1; # unbuffer for clarity autoflush ANOTHER_HANDLE 0; # buffer this for speed
The above three come with an expense as the 'use'd IO::Handle module require 1000's of lines of code to be read and compiled. It may often be better to use $| directly. But there you go, you have choice!

Additionally I should add that removing buffering does come at an expense ... speed! Computers have buffers for a reason. My rule of thumb is only to turn buffering off if its required, that is, if I'm not seeing my output when I *really* need to. And usually that's when I'm into the testing stage of a script and find I'm not seeing what I should, I then set things unbuffered.

Lastly, Perl's 'print' in an unbuffered state isn't truly unbuffered. Truly unbuffered mean every character one at a time is written. Perl's 'print' is what's called "command buffered". That is, a physical write is made after an ouput command. It means your unbuffered prints aren't as intensive on your system while still getting the results you need.

Dean
The Funkster of Mirth
Programming these days takes more than a lone avenger with a compiler. - sam
RFC1149: A Standard for the Transmission of IP Datagrams on Avian Carriers

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://344830]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (3)
As of 2024-04-26 00:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found