Perl STDOUT is redirected to the channel, without exiting after calling sleep ()

I am having problems with Perl on Windows (both ActivePerl and Strawberry) when redirecting an STDOUT script to a channel and using the sleep () function. Try the following:

perl -e "for (;;) { print 'Printing line ', $i++, \"\n\"; sleep(1); }"

This works as expected. Now drag it to Tee (or some file, same result):

perl -e "for (;;) { print 'Printing line ', $i++, \"\n\"; sleep(1); }" | tee

There is no conclusion; te does not capture anything. However, the perl script still works, only there is nothing in STDOUT until the script ends, and then all output will be flushed to tee. In addition, if the STDOUT buffer fills the script, it may hang.

Now, if you remove the dream (call), the pipe works as expected! What's happening?

I found a workaround; disable STDOUT buffering with $ | = 1 makes the pipe work when using sleep, but ... why? Can someone explain and suggest a better solution?

+3
source share
1 answer

You are suffering from buffering. Add $| = 1;STDOUT to unbuffer.

All file descriptors, except for STDERR, are buffered by default, but when connected to the terminal, STDOUT uses a minimal form of buffering (cleared by newline characters). By substituting the terminal for the pipe, normal buffering is restored.

sleep , . , , . - 4k 8k ( Perl).

+4

All Articles