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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.