|No such thing as a small change|
Perl Idioms Explained - $|++by broquaint (Abbot)
|on Aug 01, 2003 at 16:05 UTC||Need Help??|
"Perl Idioms Explained" explained
This is the first post in a series of posts that aim to explain the workings and reasoning behind common perl idioms. Each post will be relatively short but hopefully informative enough to sufficiently illuminate each idiom.
Perl Idioms Explained - $|++
It is not entirely uncommon to see this rather mysterious combination of characters following the usual pragma declarations - $|++. The most perfunctory glance will reveal that the post-increment operator is used, and a further look will show that said operator is working on the $|. Browsing through man perlvar we see that $| is defined like so
autoflush HANDLE EXPR
So the the post-increment on the $| sets it to 1 (sidenote - its value, magically, can only ever be 0 or 1) which will turn off buffering for STDOUT. The implications for turning off buffering are far reaching so if you'd like to know more about it then see Dominus' cracking Suffering from Buffering. For a simple demonstration of this idiom in action and the effects of output buffering try running the following piece of code
When that is run you should notice that with buffering the dots aren't displayed until the flush is forced with a \n, whereas without buffering the dots were displayed immediately as the output wasn't being held in an output buffer.
The $|++ idiom will turn buffering off for when we want to see our output, and we want to see it now!