The heart of Scalar::Util's openhandle() is

defined(fileno $arg)

which was my first thought. It goes a bit further to try to deal with tied file handles (that you might be able to read from, etc. even though they don't directly contain an open file descriptor).

If one wants to do something other than read/write the handle (for example: stat or select), then I'd just use defined(fileno $arg) (since stat and select aren't going to work on tied handles anyway).

My second thought was that if one just wants to read from the handle, can might offer a simple and high-quality solution. I didn't produce a working example of that because I decided my third thought was even better in that case...

eval{<$arg>} was my third thought. But testing reminded me that <...> doesn't give you any reasonable way to distinguish "end of file" from "error reading"1.

1 I first discovered this when writing a book on Perl. No, it never got finished. The editor had health problems, the publisher didn't follow through, then I no longer had time.

- tye        


In reply to Re^2: Function that accepts either a file name or a handle by tye
in thread Function that accepts either a file name or a handle by eyepopslikeamosquito

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.