Course of Raku / Advanced / Subroutines
More on MAIN subroutines
In the Essentials part you used MAIN to
receive command-line arguments. Raku does more for you around
MAIN than just passing the values in.
The usage message
If the arguments on the command line do not match the signature of
MAIN, Raku does not run the body. Instead, it prints an
automatically generated usage message that describes how the
program should be called.
Take this program:
sub MAIN($name) {
say "Hello, $name!";
}Called correctly, it greets the person:
$ raku hello.raku Anna
Hello, Anna!Called with no argument, the signature does not match, so Raku prints the usage instead of the greeting:
$ raku hello.raku
Usage:
hello.raku <name>The message is built from the names of the parameters, so giving them meaningful names makes the help text helpful for free.
Named arguments
Parameters of MAIN may be named as well as positional. A
named parameter becomes a --option=value switch on the
command line, and a default value makes it optional:
sub MAIN(:$name = 'World') {
say "Hello, $name!";
}$ raku hello.raku
Hello, World!
$ raku hello.raku --name=Raku
Hello, Raku!Practice
Complete the quiz that covers the contents of this topic.
Exercises
This section contains 3 exercises. Examine all the topics of this section before doing the coding practice.