in reply to Function that accepts either a file name or a handle


It is quite hard to check for all of the possible filehandles that could be passed to a function. In the Scalar::Util module there is a function called openhandle() that can be used to check whether the function argument is a valid filehandle.

As a less rigourous solution you could just use ref to check if the argument is a reference and then presume a filehandle. It will depend on your application.

--
John.

  • Comment on Re: Function that accepts either a file name or a handle

Replies are listed 'Best First'.
Re^2: Function that accepts either a file name or a handle
by tye (Sage) on Apr 21, 2004 at 06:52 UTC

    The heart of Scalar::Util's openhandle() is

    defined(fileno $arg)

    which was my first thought. It goes a bit further to try to deal with tied file handles (that you might be able to read from, etc. even though they don't directly contain an open file descriptor).

    If one wants to do something other than read/write the handle (for example: stat or select), then I'd just use defined(fileno $arg) (since stat and select aren't going to work on tied handles anyway).

    My second thought was that if one just wants to read from the handle, can might offer a simple and high-quality solution. I didn't produce a working example of that because I decided my third thought was even better in that case...

    eval{<$arg>} was my third thought. But testing reminded me that <...> doesn't give you any reasonable way to distinguish "end of file" from "error reading"1.

    1 I first discovered this when writing a book on Perl. No, it never got finished. The editor had health problems, the publisher didn't follow through, then I no longer had time.

    - tye        

      eval{<$arg>} was my third thought. But testing reminded me that <...> doesn't give you any reasonable way to distinguish "end of file" from "error reading".

      I don't understand how eval could be employed since the following program does not die when you read from <$fh>:

      my $fh = 'f.tmp'; my $s = <$fh>; print "i am here: s='$s'\n";

      That is, there is nothing to catch.

        That is, there is nothing to catch.

        Yes. That was why the second sentence started with "But".

        - tye