Re: Detecting filehandles



Subotai 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
}

Use fileno() for that, if it is defined then it is a valid filehandle.

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.

There is if you have a /proc file system that supports it:

$ perl -le'
open my $fh, q[test.txt] or die $!;
my $fn = fileno $fh;
print readlink "/proc/self/fd/$fn";
'
/home/john/test/test.txt

Or use the PID:

$ perl -le'
open my $fh, q[test.txt] or die $!;
my $fn = fileno $fh;
print readlink "/proc/$$/fd/$fn";
'
/home/john/test/test.txt



John
--
use Perl;
program
fulfillment
.



Relevant Pages

  • Re: threads and logfile rotation
    ... But the problem remains how to get the filehandle closed again to be ... you can probably work out an elegant loop where you write ... to the fileno, unless a shared flag is set. ...
    (comp.lang.perl.misc)
  • Re: perl problem with select and non-blocking sysread from multiple pipes
    ... > the indirect filehandle stuff is just plain confusing. ... >> What are you expecting fileno() to return for a filehandle that has ... D:\Home> perldoc -f fileno ... vec EXPR,OFFSET,BITS ...
    (comp.lang.perl.misc)
  • Re: threads and logfile rotation
    ... I assume this is because of the detached thread still referencing the ... filehandle because it got copied at thread creation. ... thread and place it's fileno in a shared variable, ...
    (comp.lang.perl.misc)
  • Re: How to tell if handle is open?
    ... >How can my script tell whether a filehandle is open? ... Check for a nonzero return value from fileno. ...
    (comp.lang.perl.misc)
  • Re: $ or % For Associative Arrays?
    ... the current version of Perl is 5.8. ... opendir and its relatives do NOT use filehandles they use directory handles ... and you cannot perform filehandle operations on a directory handle nor can you ... opendir A, 'directory' or die $!; ...
    (perl.beginners)