rovf has asked for the wisdom of the Perl Monks concerning the following question:
This example worked, but I wonder whether it worked by accident, or whether this is really portable:
This prints 1.perl -lwe 'my $h1=*STDOUT; open(my $h2, ">", "tmp/xx1.txt") or die; $h +1 eq *STDOUT && print 1; $h2 eq *STDOUT && print 2'
Background of the question: I have a variable containing a file handle. Depending on which branch the program takes, this variable is either initialized by $fh=*STDOUT or by open($fh,'>',$filename). At some later point in the program, I want to close $fh unless it is connected to STDOUT. The question is how to test this in a portable way.
Using -t $fh is not a solution, because this would test whether $fh is connected to a terminal, which is something different. By experimenting, I found that <c>$f eq *STDOUT<c> seems to do the job. However, doing string equality on a file handle looks a bit arcane to me.
BTW, the test for equality will be done in the same package than the assignment of the file handle (this might be relevant for the way the handle is turned into a string by the equality operator).
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Testing whether a file handle is attached to STDOUT
by BrowserUk (Patriarch) on Jun 16, 2011 at 10:31 UTC | |
by rovf (Priest) on Jun 16, 2011 at 10:51 UTC | |
by Corion (Patriarch) on Jun 16, 2011 at 10:55 UTC | |
by BrowserUk (Patriarch) on Jun 16, 2011 at 10:56 UTC | |
|
Re: Testing whether a file handle is attached to STDOUT
by Tanktalus (Canon) on Jun 16, 2011 at 13:51 UTC | |
by rovf (Priest) on Jun 16, 2011 at 14:01 UTC | |
|
Re: Testing whether a file handle is attached to STDOUT
by ikegami (Patriarch) on Jun 16, 2011 at 15:10 UTC |