mull has asked for the wisdom of the Perl Monks concerning the following question:
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: test if a scalar contains a filename or a filehandle?
by Cyrnus (Monk) on Apr 26, 2002 at 07:08 UTC | |
|
Re: test if a scalar contains a filename or a filehandle?
by jmcnamara (Monsignor) on Apr 26, 2002 at 08:07 UTC | |
|
Re: test if a scalar contains a filename or a filehandle?
by rjray (Chaplain) on Apr 26, 2002 at 06:51 UTC | |
|
Re: test if a scalar contains a filename or a filehandle?
by jmcnamara (Monsignor) on Apr 30, 2002 at 08:13 UTC |