Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 818
cdleary Avatar asked Apr 01 '09 19:04

cdleary


People also ask

What is if name == Main in Python?

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.

Is if name == Main necessary?

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.

What does __ main __ mean in Python?

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.

What is init Main in Python?

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.


1 Answers

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.

like image 136
cjm Avatar answered Sep 28 '22 21:09

cjm