Joe_Cullity has asked for the wisdom of the Perl Monks concerning the following question:

If I have a file handle, is their any way to convert it to the files name or better yet the full filespec ? The real problem is that my program will be passed the name of the Input/Output files by redirecting STDIN / STDOUT. ---Example: MyProg <UseAsInput >WriteDataHere--- I’d like to print the input/output file in the header of the output data. Another way to do this could involve reading the COMMAND LINE and pulling out the portion of the line after <… and >… ?

Replies are listed 'Best First'.
Re: Reverse engineering a file handle
by derby (Abbot) on Jun 09, 2005 at 19:08 UTC

    Is this a *nix platform? If so you really shouldn't even try. Sure you can muck around the /proc filesystem for answers but it seems so icky. If you really really really need the input and output filenames in our output file, then you should skip the redirection and support command line args for input and output:

    myprog --input <file> --output <file>
    -derby
Re: Reverse engineering a file handle
by gellyfish (Monsignor) on Jun 09, 2005 at 18:52 UTC

    This really depends on the operating system, for instance on Linux stat the /proc/self/fd/0 and then search the file system for a file that has the same device and inode numbers, this is really the reverse of how Linux::Fuser does it. However on other operating systems, I really don't have a clue.

    /J\

      The caveats with the above answer:

      When the above method works, it's not guaranteed to return the right name. More than one file name can have the same inode (rare), or a symbolic link might have been be used on the command line (common).

      Wouldn't that take a long time on drive with many files? (common)

      And there are times when the above approach (and all others) would fail: When STDIN and/or STDOUT isn't a file. STDIN and/or STDOUT could be associated with a pipe, a device, etc.

      Can you possibly rewrite the script and caller to pass the file names as arguments? You could make the name arguments optional and use STDIN and STDOUT when no names are provided.