Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

retrieve filename from filehandle?

by Anonymous Monk
on Jan 16, 2006 at 12:06 UTC ( #523472=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl Monks, Can we retrieve the filename just by knowing its FileHandle? Thanks in advance,

Replies are listed 'Best First'.
Re: retrieve filename from filehandle?
by zentara (Archbishop) on Jan 16, 2006 at 12:57 UTC
    What if the filehandle is a pipe, socket, or opened to a scalar, etc? I don't think there is anything that is simple and cross-platform Perl. But why would you need this? If you opened the filehandle with your script, you ought to know where it's coming from or going to. :-)

    You can get the file descriptor for the filehandle. Read "perldoc -f fileno"

    perldoc -f fileno fileno FILEHANDLE Returns the file descriptor for a filehandle, or undefined if the filehandle is not open.

    I'm not really a human, but I play one on earth. flash japh
Re: retrieve filename from filehandle?
by blazar (Canon) on Jan 16, 2006 at 13:33 UTC

    zentara told you how to get the file descriptor of your handle. Now, under Linux you can get a symlink to your original file from


    I don't know how portable this is to other unices, not to say osen - generally I expect little to zero. Still it may be suitable for you!

      A slightly more cross-platform way of doing this (works on most Unixes) would be to use lsof. The following will first determine the file descriptor from the filehandle (as per zentara's example) and then uses this file descriptor to find the file name.

      my $desc = fileno($handle); my $name = (`lsof -Fn -a -d $desc -p $$`)[1]; $name = substr($name,1);

      There are ten types of people: those that understand binary and those that don't.
      Thank you very much for that tip! Here is an example of how it could be used:
      arun@butterfly:~> perl -de 0 Loading DB routines from version 1.23 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(-e:1): 0 DB<1> open $fh, '>', 'temp.txt' DB<2> x $fh 0 GLOB(0x816b940) -> *main::$fh FileHandle({*main::$fh}) => fileno(6) DB<3> $d = fileno $fh DB<4> p $d 6 DB<5> p qx[ls /proc/$$/fd] 0 1 2 3 4 5 6 7 DB<6> p readlink("/proc/$$/fd/$d") /home/arun/temp.txt

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://523472]
Approved by prasadbabu
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2018-05-28 10:27 GMT
Find Nodes?
    Voting Booth?