On Tue, 12 Jun 2001, Charles Lu <[EMAIL PROTECTED]> wrote,

> my $oldhandle=undef;
> if($user_input ne 'STDOUT') {           #user specify output to a file
>     open (OUT,">$temp.txt") or die "Can't open the file\n";
>     $oldhandle = select OUT;
> }
>
> print "blah blah blah\n";
>
> select ($oldhandle) if(defined($oldhandle));  #restore STDOUT as default
>
> At this point I want to close my FileHandle (OUT) if it was open.  My
> question is HOW do I check to see whether a filehandle(OUT) has been opened
> so I can explicitly close it with


One way,

    print "sample 1\n";
    my $want_out_file = shift;
    my $fh = *STDOUT;
    if ($want_out_file) {
        open OUT, ">zzzfile" or die $!;
        $fh = *OUT;
    }
    print $fh "output of sample 1\n";
    close $fh if $want_out_file;


Another way,

    print "\nsample 2\n";
    put("to stdout");
    open F, ">the-F-file" or die $!;
    put("to the-F-file", \*F);
    close F;
    put("to zzzfile", 'zzzfile');

    sub put {
        my($text, $file) = @_;
        my $fh = *STDOUT; # default output stream
        my $opened;

        if (defined $file) {
            if (UNIVERSAL::isa($file, 'GLOB')) {
                $fh = $file; # $file is already opened
            } else {
                local *OUT;
                open OUT, ">$file" or die $!; # open the file ourself
                $fh = *OUT;                   # new filehandle
                ++$opened;                    # mark it for later use.
            }
        }
        print $fh "$text\n";
        $opened && close $fh;
    }

I'm sure there's more elegant way to do this.


__END__
-- 
s::a::n->http(www.trabas.com)


Reply via email to