eval{} some innocuous operation such as $fh->format_name and check if an error has been generated. That takes 'duck typing' to its logical end; A filehandle can "format_name", so let's "format_name" and see if we get an error.

However, you have to keep in mind that if $fh contains a glob that holds a string, that string will silently try to convert itself to a filehandle.

For example: $something = 'STDOUT'; *someglob = $something; $fh = \*someglob; $fh->format_name; will be accepted just fine, because $fh contains a reference to a glob that holds the STDOUT filehandle, even though it was just a string only two operations ago. In fact the third layer of indirection isn't even needed; *someglob also contains a filehandle, of course. Perl would be equally happy with *someglob->format_name. And in fact, even $something->format_name is fine with Perl; as long as the string looks like a known filehandle, it's fine.

On the other hand, $something = 'frobcinate'; $something->format_name; will throw an exception unless you've opened a filehandle named *frobcinate.

This may be a terrible oversimplification that fails to work in some important cases. Certainly it would fail if $something were blessed into a class that is nothing like a filehandle except that it has a method named format_name.


Dave


In reply to Re^5: Best way to check if something is a file handle? by davido
in thread Best way to check if something is a file handle? by tobyink

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.