The Pearls of Raku, Issue 6: MAIN and BEGIN

Another set of tiny but useful practical things that can help your coding practice in the Raku programming language. In this issue, we are talking about the MAIN function and the BEGIN phaser.

Another set of tiny but useful things that can use in your coding practice in the Raku programming language.

Table of Contents

Default MAIN

An interesting way of providing the default values to all of the parameters of the MAIN function. Just define a multi-version that takes no arguments and calls a suitable version with the parameters you want.

multi sub MAIN() {
    MAIN('User');
}

multi sub MAIN(Str $name, Str $greeting = 'Hello') {
    say "$greeting, $name!";
}

Now, running a program without the arguments gives some meaningful result.

$ raku default-main.raku 
Hello, User!

$ raku default-main.raku John
Hello, John!

You can combine this method with regular default values of the arguments. If there is no sense to run a program with no parameters, make sure you have a descriptive USAGE example.

BEGIN phraser

The BEGIN phaser can be used to print a message before the program even starts running. This may be handy, for example, if you have a few different MAIN functions and want to have a common message for all of them.

The below (rather artificial) program prints a message even if the main code fails.

BEGIN {
    say 'This program prints the result of division by zero.';
}

multi sub MAIN() {
    say 42/0;
}

multi sub MAIN(Int $n) {
    say $n / 0;
}

Find the code of this issue on GitHub and browse for more Raku Pearls.

One thought on “The Pearls of Raku, Issue 6: MAIN and BEGIN”

Leave a Reply to Michael Cancel reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code