Perl的打印缓冲刷新

5

I have the following Perl code:

STDOUT->autoflush(1);

foreach(...)
{
    ...

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

但是print语句只在循环的第一次迭代中起作用,之后不再打印任何内容。有什么想法吗?

编辑:我已经找到了原因,并在答案中添加了它。

解决方案如下:

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...


你确定有多于一次的迭代吗? - innaM
是的,有不止一次迭代。我尝试添加警告语句,但它被打印了多次。 - Manoj
找到了问题。请看下面的答案。 - Manoj
3个回答

11

非常感谢你在追踪问题时进行了出色的侦查工作!

我想提出另一种解决方案。

process() 的作者进行 select() 斗争不如使用 IO::Handle 接口到 STDOUT:

use IO::Handle;

foreach(...)
{
    ...

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

        process($folder);
    }
    ...
}

5

我在循环内添加了以下行,并且它起作用了:

select STDOUT;

我认为process()函数中的代码应该修改默认输出缓冲区。这是由其他人编写的代码!

我不确定这是否是Perl允许这种情况的问题,还是开发人员没有将其改回默认设置。

最终的代码如下:

foreach(...)
{
    ...

    foreach(...)
    {
        select STDOUT;

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

Thanks all...


0
我的代码看起来像这样:
#!/usr/bin/perl -w

use strict;
use warnings;
use sigtrap qw/handler signal_handler normal-signals/;
use feature qw(say);

my $datetime;
$datetime = localtime ();

say "tester started $datetime";

while ( 1 ) {
    select STDOUT;
    $datetime = localtime ();
    say "tester output every second $datetime";
    $|=1;
    sleep ( 1 );
}

sub signal_handler {
    die "\nCaught a signal $!\n";
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接