I know Perl has a design pattern known as a modulino, in which a library module file can act as both a library and a script. Is there any equivalent to this in Ruby / Python?
I think this design pattern would be very useful for me; I'm writing workers that are fairly short, but also require a script to run them. I think it would be convenient to have this all run from the same place.
Thank you!
Python has
__name__
:If you run
python myscript.py
, theprint
function will run. If you importMyClass
frommyscript
, theprint
will not.Perl 6 has this feature built in. You define a subroutine named
MAIN
that executes if you use the file as a script: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:This is the Ruby version: