in reply to Filehander Question

EchoAngel,
One way to do this is to make STDOUT the default, but allow the user to overide.
#!/usr/bin/perl use strict; use warnings; use Getopt::Std; my $opt = {}; Get_Args( $opt ); my $fh; if ( $opt->{o} ) { open ( $fh, '>', $opt->{o} ) or die "Unable to open $opt->{o} for +writing : $!"; } else { open ( $fh, '>&', *STDOUT ) or die "Unable to dup STDOUT : $!"; } select $fh; $| = 1; print "foo bar\n"; sub Get_Args { my $opt = shift; my $Usage = qq{Usage: $0 [options] -h : This help message. -o : Output file - STDOUT by default } . "\n"; getopts( 'ho:' , $opt ) or die $Usage; die $Usage if $opt->{h}; }

Cheers - L~R

Note: The lexical FD, 3 arg open, and specifically '>&' are new in more recent versions of Perl. It is trivial to modify if you want to support older versions

Replies are listed 'Best First'.
Re^2: Filehander Question
by ikegami (Patriarch) on Oct 07, 2004 at 15:33 UTC

    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;

      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; }