Another set of tiny but useful things that can use in your coding practice in the Raku programming language.
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.
In the first example, you might as well say:
sub MAIN(Str $name = ‘User’, Str $greeting = ‘Hello’)