in reply to print inside a loop

Often printing will be done immediately if you finish your text with an \n:
print "\nChecking something - \n";
HTH, Rata

Replies are listed 'Best First'.
Re^2: print inside a loop
by Eliya (Vicar) on Feb 22, 2011 at 12:22 UTC
    Often...

    More specifically, when the buffering mode is set to "line-buffered" — which is the default with interactive things like terminals.

    In general, and to summarize, there are three buffering modes:

    • unbuffered — when explicitly requested, and the default for stderr
    • line-buffered — the default in interactive contexts
    • block-buffered (aka "fully buffered") — the default for everything else, like writing to files, pipes, etc.

    In block-buffered mode, flushing doesn't happen before the respective buffer, e.g. 4k bytes size, has filled up.

    For example (block-buffered):

    $ strace -ewrite perl -E 'say "X"x99 for 1..100' >/dev/null write(1, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"..., 4096) = 4096 write(1, "XXX\nXXXXXXXXXXXXXXXXXXXXXXXXXXXX"..., 4096) = 4096 write(1, "XXXXXXX\nXXXXXXXXXXXXXXXXXXXXXXXX"..., 1808) = 1808

    Without the redirect of stdout, i.e. when it's connected to the terminal, you'd see 100 write system calls à 100 bytes... (line-buffered)

      Can one explicitly set buffering to line- or buffer oriented, or is that chosen by the system, and all you can do is enable/disable buffering by assigning a boolean value to $|?

      I guess the system choses, perhaps based on the -t flag, but I'm not sure at all.

        AFAIK, since the advent of PerlIO (which almost all perls are compiled/configured for these days), Perl chooses itself between block- or line-buffered, and you can only select unbuffered vs. the other two (with $|).

        In earlier versions of Perl, when stdio (C runtime lib) was used by default, you could use setvbuf (via IO::Handle) to set buffering mode and buffer size.

        These days, you usually get:

        $ perl -MIO::Handle -e 'STDOUT->setvbuf($buf, _IOLBF, 2**16)' IO::Handle::setvbuf not implemented on this architecture at -e line 1.