Equivalent to Perl Modulino for Ruby, Python?

僤鯓⒐⒋嵵緔 提交于 2019-12-05 19:42:02

Python has __name__:

class MyClass(object):
    pass

if __name__ == '__main__':
    print("This will only run if you run the script explicitly, not import it")

If you run python myscript.py, the print function will run. If you import MyClass from myscript, the print will not.

This is the Ruby version:

if __FILE__ == $PROGRAM_NAME #equivalent: if __FILE__ == $0
  puts "This is the main file running, it is not being required."
end

Perl 6 has this feature built in. You define a subroutine named MAIN that executes if you use the file as a script:

 sub MAIN { ... }

The signature for MAIN tells Perl 6 how to parse the command-line parameters. You can have multi-subs and Perl 6 will use the one whose signature matches. Here's the example from Synopsis 6:

multi MAIN (Int $i) {...}   # foo 1
multi MAIN (Rat $i) {...}   # foo 1/2
multi MAIN (Num $i) {...}   # foo 1e6
multi MAIN ($i) {...}       # foo bar
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!