Daniel C. Sobral
Daniel C. Sobral

Reputation: 297265

How do I get the name of the file being read in Perl?

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.

Upvotes: 2

Views: 1386

Answers (3)

Todd Hunter
Todd Hunter

Reputation: 881

It is stored in

$ARGV

See perldoc perlvar:

  • $ARGV

It 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.

Upvotes: 17

Michiel Buddingh
Michiel Buddingh

Reputation: 5919

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

It is useful, but only in cases where input for the Perl script is read from standard input. This can be determined by reading $ARGV, as described in the replies above.

Upvotes: 2

Pod
Pod

Reputation: 4129

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

Upvotes: 2

Related Questions