Is there a Perl equivalent to Python's `if __name__ == '__main__'`?

前端 未结 3 2088
北恋
北恋 2021-02-06 23:31

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__ == \'__m         


        
相关标签:
3条回答
  • 2021-02-06 23:52

    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.

    0 讨论(0)
  • 2021-02-06 23:54

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

    0 讨论(0)
  • 2021-02-07 00:05
    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.

    0 讨论(0)
提交回复
热议问题