Manoj Manoj - 5 months ago 20
Perl Question

Perl Print buffering flush

I have the following Perl code:

STDOUT->autoflush(1);

foreach(...)
{
...

foreach(...)
{
print("Processing $folder");
$|=1;
process($folder);
}
...
}


but the print statement works only in the first iteration of the loop and does not print anything after that. Any idea why?

EDIT: I found the reason and have added it in the answer also.
The solution was:


I added the following line inside the
loop and it worked:

select STDOUT;

I think the code in process() function
should have been modifying the default
output buffer. It was a code written
by somebody else!

I am not sure if this is a problem
with Perl which allows this or the
developer who did not change it back
to the default.

The final code looked like this:

foreach(...)
{
...

foreach(...)
{
select STDOUT;

print("Processing $folder");
$|=1;
process($folder);
}
...
}


Thanks all...

Answer

Good detective work in tracking down this problem!

I'd like to suggest an alternate solution.

Rather than having select() wars with the author of process(), you could use the IO::Handle interface to STDOUT:

use IO::Handle;

foreach(...)
{
    ...

    foreach(...)
    {
        STDOUT->printflush("Processing $folder");

        process($folder);
    }
    ...
}
Comments