Generally, is it considered good Perl interface style for a function to accept either a file name or a handle? If so, what is the best way to implement it?

Test program follows.

use strict; ### DoFile. Test passing either a file name or a handle. ### Return the file contents. sub DoFile { my $fh = shift; local $/; if (UNIVERSAL::isa($fh, 'GLOB') || UNIVERSAL::isa(\$fh, 'GLOB')) { warn "DoFile: param is a glob\n"; return <$fh>; } else { warn "DoFile: param is NOT a glob\n"; local *F; open(F, $fh) or die "error: open '$fh': $!"; my $s = <F>; close(F) or die "error: close '$fh': $!"; return $s; } } my $file = 'f.tmp'; # test file warn "*** Case 1: pass a GLOB\n"; open(G, $file) or die "error: open $file: $!"; warn "contents: '" . DoFile(*G) . "'\n"; close(G) or die "close $file failed: $!"; warn "*** Case 2: pass a GLOB reference\n"; open(G, $file) or die "error: open $file: $!"; warn "contents: '" . DoFile(\*G) . "'\n"; close(G) or die "close $file failed: $!"; warn "*** Case 3: pass an autovivified scalar\n"; if ($] < 5.006) { warn "skip, perl version less than 5.006\n"; } else { open(my $fh, $file) or die "error: $file open: $!"; warn "contents: '" . DoFile($fh) . "'\n"; } warn "*** Case 4: pass an IO::File handle\n"; { require IO::File; my $fh = IO::File->new(); $fh->open($file) or die "error: open $file: $!"; warn "contents: '" . DoFile($fh) . "'\n"; } warn "*** Case 5: pass a file name\n"; warn "contents: '" . DoFile($file) . "'\n";

In reply to 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.