In Command line interface§
See primary documentation in context for sub MAIN.
The sub with the special name MAIN will be executed after all relevant entry phasers (BEGIN, CHECK, INIT, PRE, ENTER) have been run and the mainline of the script has been executed. No error will occur if there is no MAIN sub: your script will then just have to do the work, such as argument parsing, in the mainline of the script.
Any normal exit from the MAIN sub will result in an exit code of 0, indicating success. Any return value of the MAIN sub will be ignored. If an exception is thrown that is not handled inside the MAIN sub, then the exit code will be 1. If the dispatch to MAIN failed, a usage message will be displayed on STDERR and the exit code will be 2.
The command line parameters are present in the @*ARGS dynamic variable and may be altered in the mainline of the script before the MAIN unit is called.
The signature of (the candidates of the multi) sub MAIN determines which candidate will actually be called using the standard multi dispatch semantics.
A simple example:
# inside file 'hello.raku' sub MAIN($name) { say "Hello $name, how are you?" }
If you call that script without any parameters, you get the following usage message:
$ raku hello.raku Usage: hello.raku <name>
However, if you give a default value for the parameter, running the script either with or without specifying a name will always work:
# inside file 'hello.raku' sub MAIN($name = 'bashful') { say "Hello $name, how are you?" }
$ raku hello.raku Hello bashful, how are you?
$ raku hello.raku Liz Hello Liz, how are you?
Another way to do this is to make sub MAIN a multi:
# inside file 'hello.raku' multi MAIN() { say "Hello bashful, how are you?" } multi MAIN($name) { say "Hello $name, how are you?" }
Which would give the same output as the examples above. Whether you should use either method to achieve the desired goal is entirely up to you.
If you want to pass an indeterminate number of parameters to be dealt with in sub MAIN, you can use slurpy parameters:
# inside file 'hello-all.raku' sub MAIN(*@all) { for @all -> $name { say "Hello, " ~ $name } }
$ raku hello-all.raku peter paul mary Hello, peter Hello, paul Hello, mary
In Functions§
See primary documentation in context for sub MAIN.
Declaring a sub MAIN is not compulsory in Raku scripts, but you can provide one to create a command line interface for your script.