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!
if __name__ == "__main__" in ActionWe use the if-statement to run blocks of code only if our program is the main program executed. This allows our program to be executable by itself, but friendly to other Python modules who may want to import some functionality without having to run the code.
The Reason Behind if __name__ == '__main__' in Python You might have seen this one before: the syntax which often gets ignored because it doesn't seem to hinder the execution of your code. It may not seem necessary, but that's only if you're working with a single Python file.
In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
Every Python module has it's __name__ defined and if this is '__main__', it implies that the module is being run standalone by the user and we can do corresponding appropriate actions. If you import this script as a module in another script, the __name__ is set to the name of the script/module.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With