1. Perl
  2. builtin functions
  3. here

__FILE__ - Get the script file name

Use __FILE__ to get the file name of the script.

__FILE__

When you load a file as a script, the program expands into memory in the process space, but Perl remembers the filename before it was expanded.

Example

This is an example to get the file name of the script.

# Get file name __FILE__
print "1: Get the file name. (__FILE__)\n";
print "This file name is\n".
  __FILE__ . "\n".
  ".\n\n";

print "2: Get the name of the read file.\n";
# Use do to read another file into the memory of the process space of this program.
do "SomeModule.pm";

print "The read file name is\n",
  SomeModule::this_file_name (), "\n",
  ".\n\n";

print '3: Not the name of the script being executed ($0). ' . "\n";
print "The name of the script being executed is\n",
  SomeModule::this_script_name (), "\n",
  ".\n";

SomeModule.pm (Place it in the same directory as the example script above)

package SomeModule;

use strict;
use warnings;

sub this_file_name {
  return __FILE__;
}

sub this_script_name {
  return $0;
}

1;

Related Informatrion