After spending what felt like a long time browsing through the documentation and so on I think I figured this out on my own, but now the time has come to ask for some enlightenment...

I am trying to write a subroutine that will accept either a filename to be opened and read from, or an already opened filehandle to just read from. My problem at first seemed to be that I had a poor understanding of what filehandles really were; but now after reading up on symbol tables I think I have that part fairly clear. What I am wondering is if there is a much better way to do this... or maybe there is already a module that does this, but I couldn't find one. Here is what I have come up with so far:

# I am running with perl -w && strict BTW sub read_file_or_handle { my $file_or_handle = shift; chomp $file_or_handle; unless(open FH, $file_or_handle ) { no strict q(refs); *FH = *file_or_handle; } while (<FH>) { ... } close FH; # closes it no matter what is was, right? # return something I read }

One thing I don't like about this right away is that I am assuming I have an open filehandle based on the failed call to open. I'm used to more of an "open or die" construct, so I know that I'm opening my self up to trouble right there. Suggestions?


In reply to test if a scalar contains a filename or a filehandle? by mull

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.