in reply to Re: Filehander Question
in thread Filehander Question

Your code has a side effect.
print $fh ('test');
and
print('test');
both end up in the file, when a filename is specified. I don't think that was your intention.

To set auto-flushing, do
{ my $f = select($fh); $|=1; select($f); }
instead of
select($fh); $|=1;

Replies are listed 'Best First'.
Re^3: Filehander Question
by Limbic~Region (Chancellor) on Oct 07, 2004 at 15:38 UTC
    ikegami,
    That isn't a side effect, that is the primary effect. I interpreted EchoAngel's request as I don't want to have to change anything other than -o "somefile" to get all my existing prints to DWIM. I guess you took my comment in the CB about needing select to do auto-flushing to mean that is the only reason I did it - sorry.

    Cheers - L~R

      Why bother duping STDOUT, then?
      my $fh; if ( $opt->{o} ) { open ( $fh, '>', $opt->{o} ) or die "Unable to open $opt->{o} for writing : $!"; select($fh); $| = 1; }
        ikegami,
        Well, it was intended as an unspoken excersise for the reader/EchoAngel. By using a lexical FD, I thought it would be possible to make the magic work for only certain parts of the code and that when it fell out of scope Perl would DWIM and revert back to STDOUT.

        As I was replying to this node I thought I better check it - turns out that it doesn't do what I thought it would. Subsequent prints to a lexical file handle that was selected but has gone out of scope still goes to that filehandle instead of reverting back to STDOUT. In light of this new discovery, the dup of STDOUT is not necessary, but it still had value - I learned something cool.

        Cheers - L~R