melguin has asked for the wisdom of the Perl Monks concerning the following question:

There is a script that I am trying to troubleshoot that sometimes waits to write a line previously printed to the filehandle until the filehandle is closed.

At the end of the script it does this:

print FILE (scalar localtime)." ## Exit\n"; close FILE;
which results in a line previously previously printed to be written to the file after the Exit line. However, if I do this:
print FILE (scalar localtime)." ## Exit\n"; exit(); close FILE;
everything is fine. It's probably not a good idea to exit before the close, so I'm looking for another way to get the same results.

many thanks great holders of wisdom.

Replies are listed 'Best First'.
Re: output caught in memory
by Wookie (Beadle) on Jul 26, 2001 at 20:33 UTC
    The easiest way to make sure the write occurs is to write it in two lines - and set your write buffers to instant write.

    So try this:
    $|=1; # $| is undef by default - which means use buffering - define it + as 1 - and it instantly writes. print FILE scalar localtime; print FILE " ## Exit\n"; close FILE;
    Alternatively, you can try to build the entire entry into a variable first - then write it. So:
    $close = localtime; print FILE "$close ## Exit\n"; close FILE;
    I hope this helps :).

    Update: Remove quotes around scalar localtime in first code block (thanks MZSanford)
    game(Wookie,opponent) eq 'Wookie' ? undef $problem : remove_limbs(arms,opponent);
Re: output caught in memory
by dragonchild (Archbishop) on Jul 26, 2001 at 20:38 UTC
    Or, if you used IO::File, just do something like:

    use IO::File; my $output = IO::File->new(">&STDOUT"); autoflush $out; print $out "Some String\n"; $out->close;
(jeffa) Re: output caught in memory
by jeffa (Bishop) on Jul 26, 2001 at 20:34 UTC
    Wrong answer - move along, nothing to see here . . .

    You can try END:

    sub END { close FILE; }

    Jeff

    R-R-R--R-R-R--R-R-R--R-R-R--R-R-R--
    L-L--L-L--L-L--L-L--L-L--L-L--L-L--
    
Re: output caught in memory
by melguin (Pilgrim) on Jul 26, 2001 at 20:43 UTC
    great.

    I had looked at the $| option and had declared it equal to 1 at the beginning of the script, but it didn't do anything (perhaps because I was using select to change the default output before printing?).

    What finally worked was adding the $| = 1 between the selects. So, I went from this:

    # Change the output to logfile $filehandle = select LOG_FILENAME; eval $menu[$var]; # Restore the filehandle select $filehandle;
    to this:
    # Change the output to logfile $filehandle = select LOG_FILENAME; $| = 1; eval $menu[$var]; # Restore the filehandle select $filehandle;
    Many thanks to all.