This example worked, but I wonder whether it worked by accident, or whether this is really portable:
perl -lwe 'my $h1=*STDOUT; open(my $h2, ">", "tmp/xx1.txt") or die; $h +1 eq *STDOUT && print 1; $h2 eq *STDOUT && print 2'
This prints 1.

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).

-- 
Ronald Fischer <ynnor@mm.st>

In reply to Testing whether a file handle is attached to STDOUT by rovf

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.