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

If I call a script from the command line as follows:
perl process.pl input.txt > output.txt
...the name of the perl script being executed is in $0 and the name of the input file can be easily extracted from @ARGV. But is there any way of getting at the output filename? E.g.
while (<>) { print "Reading from: $ARGV, Writing to: $???\n"; }
I understand that under normal circumstances it is not possible to extract a filename from a filehandle - but if the name is being passed via the command line as here, is there (or should there be?) a convenient way of retrieving it?

janitored by ybiC: Retitle from "Missing special variable?" for searchability

Replies are listed 'Best First'.
Re: Get filename of STDOUT
by Joost (Canon) on Aug 10, 2004 at 17:37 UTC
    On unix the command line is parsed by the shell first, so your program only sees the "input.txt" part, and your perl code only has the file handle. A recent discussion in the ChatterBox on the subject brought up the lsof Unix command, but I wouldn't call it convenient, and usually needs root permissions.

    Another possibilty is to use stat to get the Inode number and then search the filesystem for the corresponding file. I don't know if that works for multiple file-systems, though.

    Can't you rewrite your program as taking 2 filenames as arguments? It seems the most convenient by far.

    J.

Re: Missing special variable?
by etcshadow (Priest) on Aug 10, 2004 at 17:52 UTC
    Well, it's highly non-portable, but on linux, you can find this by looking on the proc filesystem and traversing a symlink. You can find the file name of the file to which STDOUT is attached by readlink "/proc/$$/fd/1";. Demonstrated as:
    [me@host]$ perl -le 'my $outputfile = readlink "/proc/$$/fd/1"; print +STDERR $outputfile;' > t1 /home/me/t1 [me@host]$
    That is... look into this process (/proc/$$), examine its filehandles (/proc/$$/fd). In particular, look at its filehandle number 1 (the fileno of STDOUT). This will be a symlink to the actual file that STDOUT is opened to (hence the readlink).
    ------------ :Wq Not an editor command: Wq
Re: Get filename of STDOUT
by pelagic (Priest) on Aug 10, 2004 at 17:35 UTC
Re: Get filename of STDOUT
by gaal (Parson) on Aug 10, 2004 at 17:42 UTC
    Bad news: even $0 won't work on all platforms. Win32, notably, does not support it.
      Bad news: even $0 won't work on all platforms. Win32, notably, does not support it.
      ActivePerl 808 on Windows seems to support $0.
        Really? What does it say? (For named scripts; for one-liners?) Can you modify it?

        Last time I checked it said something useless like "perl.exe" or maybe nothing at all. That was in some 5.6 ActivePerl.