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

I know that usage of IO::Handle provides the flush() method, so you can do $fh->flush(); whenever you want. However, as far as I can tell, flush() is implemented within IO.xs as fflush(). There doesn't seem to be a PurePerl way to just flush a filehandle.

I would love to proven wrong, though.

Update: I am proven wrong. Shows that you should treat SoPW as a teddy bear, hit Preview instead of Update, and wait 10 minutes. (Could this be a feature request?)

sub flush { my $fh = shift; my $old_fh = select $fh; local $|++; print $fh q{}; select $old_fh; return 1; }

My criteria for good software:
  1. Does it work?
  2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

Replies are listed 'Best First'.
Re: flushing a filehandle in PurePerl
by ikegami (Patriarch) on Feb 17, 2006 at 16:48 UTC
    • print $fh q{}; is not needed. Turning autoflush on causes an immediate flush.

    • $|++ is misleading. It implies $|-- will turn off autoflush, but it doesn't always. Be clear and use $| = 1 instead.

    • local $|++; is a compile error. ("Can't modify postincrement (++) in local".)

    • My tests shows that local $|; won't do what you think on block exit. It will set the autoflush flag for whichever file handle is selected when the blocks exits. That's the wrong handle.

    Use this:

    sub flush { my $osh = select($_[0]); my $oaf = $|; $| = 1; $| = $oaf; select($osh); return 1; }

    Update: Added last two bullets and the code snippet.

Re: flushing a filehandle in PurePerl
by PodMaster (Abbot) on Feb 17, 2006 at 16:07 UTC
    I hit comment, and bam, nothing left for me to write :) Well, flush Returns "0 but true" on success, "undef" on error., so you ought to capture the return value of print...

    MJD says "you can't just make shit up and expect the computer to know what you mean, retardo!"
    I run a Win32 PPM repository for perl 5.6.x and 5.8.x -- I take requests (README).
    ** The third rule of perl club is a statement of fact: pod is sexy.

Re: flushing a filehandle in PurePerl
by salva (Canon) on Feb 17, 2006 at 16:05 UTC
    maybe that will work:
    select FOO; $| = 1; print FOO "";