in reply to Re^2: Buffered, bruised and broken
in thread Buffered, bruised and broken

When STDOUT is connected to a terminal then it is "hot" by default and perl flushes its buffer when "\n" is written, but when it is not connected to a terminal, as when you redirect STDOUT to the file, then it is not "hot" by default and perl does not, by default, flush its buffer when "\n" is written. You can make it "hot" by setting "$|" to a true value (e.g. 1).

You can use strace, on linux, to see when perl writes to the system. When I run your test program under strace I get the following:

[ian@alula ~]$ strace perl ./test.pl >test.log ... write(1, "From C: 1\n", 10) = 10 write(1, "From C: 3\n", 10) = 10 write(1, "From C: 5\n", 10) = 10 write(1, "From C: 7\n", 10) = 10 write(1, "From C: 9\n", 10) = 10 write(1, "From perl: 0\nFrom perl: 2\nFrom p"..., 65) = 65 exit_group(0) = ?

Note that all the output from perl appears in a single write to the system. In this case, perl flushes its partially filled buffer as it prepares to exit.

If I add "$| = 1;", then the strace output ends as follows.

write(1, "From C: 1\n", 10) = 10 write(1, "From perl: 2\n", 13) = 13 write(1, "From C: 3\n", 10) = 10 write(1, "From perl: 4\n", 13) = 13 write(1, "From C: 5\n", 10) = 10 write(1, "From perl: 6\n", 13) = 13 write(1, "From C: 7\n", 10) = 10 write(1, "From perl: 8\n", 13) = 13 write(1, "From C: 9\n", 10) = 10 exit_group(0) = ?

In this case, because STDOUT was made "hot" by setting $| to 1, perl flushed its buffer to the system every time "\n" was written.

Replies are listed 'Best First'.
Re^4: Buffered, bruised and broken
by ikegami (Patriarch) on Jan 24, 2009 at 22:59 UTC

    In this case, because STDOUT was made "hot" by setting $| to 1, perl flushed its buffer to the system every time "\n" was written.

    That's not quite true. By setting $| to 1, Perl flushes the buffer every time anything is written. There are three states, not two:

    $ strace perl -e'$|=0; print for "a", "b\n", "c\n"' >/dev/tty write(1, "ab\n", 3) = 3 write(1, "c\n", 2) = 2 $ strace perl -e'$|=0; print for "a", "b\n", "c\n"' >/dev/null write(1, "ab\nc\n", 5) = 5 $ strace perl -e'$|=1; print for "a", "b\n", "c\n"' write(1, "a", 1) = 1 write(1, "b\n", 2) = 2 write(1, "c\n", 2) = 2
Re^4: Buffered, bruised and broken
by syphilis (Archbishop) on Jan 24, 2009 at 22:25 UTC
    ... when you redirect STDOUT to the file, then ... perl does not, by default, flush its buffer when "\n" is written.

    Aaah, I see. Thanks ig, kennethk.

    Cheers,
    Rob