Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: The delay of printing encountered using loop

by Perlbotics (Chancellor)
on Jun 25, 2012 at 21:54 UTC ( #978289=note: print w/replies, xml ) Need Help??

in reply to The delay of printing encountered using loop

I seems that perl does not flush a printed string without seeing a NL character, is that the right interpretation of this peculiar behavior?
Correct. It's the expected behaviour of STDOUT to operate in buffered mode. NL marks the end of the line and then the whole line is printed.
Can this be considered as a bug then?
Maybe not, with the weak excuse that it has been always working like that.

Buffering has some performance advantages when giving bigger chunks of characters to the OS rather than calling some I/O function of the OS for each individual character.

You can switch off buffering, setting $| to true.

perl -e '$|=1; for($i=0; $i < 10; $i++){sleep 1; print $i;}'

STDERR is unbuffered by default, so this works too (but uses a different stream):

perl -e 'for($i=0; $i < 10; $i++){sleep 1; print STDERR $i;}'

Here's the obligatory article: Suffering from Buffering

Replies are listed 'Best First'.
Re^2: The delay of printing encountered using loop
by Diamondust (Novice) on Jun 26, 2012 at 12:24 UTC
    That's very interesting.
    I guess my initial experience on Turbo C gave me this opposite feeling.
    #include <stdio.h> /* #include <unistd.h> */ main(){ while(1){ sleep(1); printf("123"); } return 0; }

    The above code, when running on Windows Turbo C, it prints 123 every second without the necessity of a NL character. But when compiled on g++ on Unix, it never prints anything because of no NL for the stream to be flushed.

    But ActicePerl on Windows has the same behavior as on Unix, i.e. it prints nothing without seeing an NL character.

    Is this because Perl tries hard to make itself platform independent, or it's because that Turbo C is archaic and has such different behavior than every one else?

      I would guess it's Turbo C being not so turbo...

      (It's not g++'s fault. It's the C library's fault. Back in DOS-land, compilers actually came with their own C libraries.[citation needed] Perl emulates its own print commands, and with it, has its own output buffers.)

        I see.
        I don't bother to install Visual C++ and test the result then -- it's too large.
        Maybe Microsoft decides to write its own library in a complete different behavior.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://978289]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2018-05-22 23:53 GMT
Find Nodes?
    Voting Booth?