tags:

views:

131

answers:

3

In the following Perl pattern:

while(<>) {
  # do stuff
}

is there a way to get the name of the file that is presently open?

Just to be clear, I expect to receive many args, so that loop will process more than one file. I want the name of the file presently being processed.

+2  A: 

If you're using linux, you can take a look at the file pointed to by /proc/self/fd/0.

Edit: Answer amended for clarity: The above is useful, but only in cases where input for the perl script is read from stdin. This can be determined by reading $ARGV, as described in the replies above.

Michiel Buddingh'
Reason for the downvote? If a file is redirected from stdin, this will give the OP a link to the file.
Michiel Buddingh'
First you have to say how to work out whether you're reading from stdin or not. The OP clearly does not expect to be reading most files from stdin, and your answer does not help when he is not reading from stdin.
Dave Hinton
The original post didn't specify that the OP was reading the files specified in the command-line arguments; it only mentioned reading from <>. But I'll grant that my answer was (and is) incomplete. Just didn't think it was incorrect.
Michiel Buddingh'
+14  A: 

It is stored in

$ARGV

See perldoc perlvar:

  • $ARGV

    contains the name of the current file when reading from <>.

However if are piping in from STDIN you will get only '-'

There is also more discussion on the null filehandle in perldoc perlop

Todd Hunter
Funny, I never realized $ARGV, as opposed to @ARGV meant something.
Daniel
@Daniel: `perldoc` should be installed on your system. You should do `perldoc perltoc` and read at least the main documentation once.
Sinan Ünür
+2  A: 

$ARGV contains the name of the file used in <>.

Pod