eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
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";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Function that accepts either a file name or a handle
by Anonymous Monk on Apr 21, 2004 at 03:43 UTC | |
|
Re: Function that accepts either a file name or a handle
by ysth (Canon) on Apr 21, 2004 at 03:55 UTC | |
|
Re: Function that accepts either a file name or a handle
by jmcnamara (Monsignor) on Apr 21, 2004 at 06:10 UTC | |
by tye (Sage) on Apr 21, 2004 at 06:52 UTC | |
by eyepopslikeamosquito (Archbishop) on Apr 21, 2004 at 08:25 UTC | |
by tye (Sage) on Apr 21, 2004 at 18:34 UTC | |
|
Re: Function that accepts either a file name or a handle
by runrig (Abbot) on Apr 21, 2004 at 16:55 UTC |