32

Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:

if __name__ == '__main__':
    # This file is being executed.
    raise NotImplementedError

I can hack something together using FindBin and __FILE__, but I'm hoping there's a canonical way of doing this. Thanks!

brian d foy
  • 129,424
  • 31
  • 207
  • 592
cdleary
  • 69,512
  • 53
  • 163
  • 191

3 Answers3

49
unless (caller) {
  print "This is the script being executed\n";
}

See caller. It returns undef in the main script. Note that that doesn't work inside a subroutine, only in top-level code.

cjm
  • 61,471
  • 9
  • 126
  • 175
10

See the "Subclasses for Applications (Chapter 18)" portion of brian d foy's article Five Ways to Improve Your Perl Programming.

Community
  • 1
  • 1
Chas. Owens
  • 64,182
  • 22
  • 135
  • 226
4

unless caller is good, but a more direct parallel, as well as a more explicit check, is:

use English qw<$PROGRAM_NAME>;

if ( $PROGRAM_NAME eq __FILE__ ) { 
    ...
}

Just thought I'd put that out there.

EDIT

Keep in mind that $PROGRAM_NAME (or '$0') is writable, so this is not absolute. But, in most practice--except on accident, or rampaging modules--this likely won't be changed, or changed at most locally within another scope.

Axeman
  • 29,660
  • 2
  • 47
  • 102
  • That's not guaranteed to work. For one thing, $0 (the real name of $PROGRAM_NAME) is actually a writable variable in Perl. But __FILE__ isn't affected by changing $0. – cjm Apr 02 '09 at 15:37
  • Not only is $0 mutable, [so is `__FILE__`](http://perldoc.perl.org/perlsyn.html#Plain-Old-Comments-%28Not%21%29). – tchrist Oct 30 '10 at 20:31