Re: Detecting filehandles




"Kevin Michael Vail" <kevin@xxxxxxxxxx> wrote in message
news:kevin-A5F7F3.21594228042006@xxxxxxxxxxxxxxxxxxx
In article <48mdnTde3IAuLM_ZnZ2dnUVZ_s6dnZ2d@xxxxxxxxxxxx>,
"Subotai" <subotai@xxxxxxx> wrote:

Is there a way to detect if an argument you are passed in a subroutine is
a
filehandle? For instance:

open(FILE, '/file');
foo(\*FILE);
foo($someotherarg);

sub foo {
$arg = shift;
#### do some check on $arg to see if it is a filehandle or a normal
scalar
}

Look at the 'openhandle' function in Scalar::Util.

Also if you have an open filehandle, is there a way to see what file it
is
referencing? For instance if you open the file "/foo", is there anyway to
get "/foo" from the filehandle? I know with the fileno() call you can get
the file descriptor, is there anyway you could use that to lookup that
information? I don't think there is but I want to be 100% sure.

I don't believe there is, either. It would be difficult to impossible
to implement under Unix, because a file is one thing and its name is
something else; in fact a file can have multiple names (directory
entries), so how would you choose which one is "the" file?

No, but no reason you can't just use a hash to store all the information
about the file and then pass that into the subroutine:

[untested]

my %fileinfo = (filepath => '/somefile.dat');
open ($fileinfo{'filehandle'}, '<', '$fileinfo{'filepath'}) or die $!;
mySub(\%fileinfo);

sub mySub {

my ($arg1) = @_;

if (ref($arg1) eq 'HASH' and defined($arg1->{'filehandle'}) {
# have a filehandle
}
else {
# do not have a filehandle
}

}


Matt


.



Relevant Pages

  • Re: Detecting filehandles
    ... $arg = shift; ... do some check on $arg to see if it is a filehandle or a normal scalar ...
    (comp.lang.perl.misc)
  • Re: Too many open files on OpenBSD
    ... i suppose the src of the parse function helps (probably disobeying all ... for line in fileHandle do ... nil # comment ... @rootNode.addRunFile arg ...
    (comp.lang.ruby)
  • Re: Detecting filehandles
    ... do some check on $arg to see if it is a filehandle or a normal scalar ... Use fileno() for that, if it is defined then it is a valid filehandle. ... $ perl -le' ...
    (comp.lang.perl.misc)
  • Detecting filehandles
    ... do some check on $arg to see if it is a filehandle or a normal scalar ... Also if you have an open filehandle, is there a way to see what file it is ...
    (comp.lang.perl.misc)
  • Re: Detecting filehandles
    ... because it is not possible to pass a filehandle as a ... That is passing a reference to a typeglob. ... do some check on $arg to see if it is a filehandle or a normal scalar ... A filehandle might correspond to a file, ...
    (comp.lang.perl.misc)