What is the proper way to load Raku modules using rakudo-star?

New Raku versions uses the .rakumod as file extension for modules. The older .pm6 extension is still supported. More information regarding the new file extensions can be found in the Path-to-Raku ticket. More information about modules is available in the raku documentation.


There are several problems.

  1. Modules don't end with .raku. They end with .rakumod or .pm6 (for now).
    (Technically after you install, it doesn't actually matter what the extension is as long as you have it properly declared in META6.json.)

  2. Subroutines are lexically scoped by default (my), and are also not exported by default.
    So there is no way to access hello() outside of the module it is defined in.

  3. Modules don't have methods, so you can't call hello as a method.
    Even if they did have methods they wouldn't start with the sub keyword.


You can globally scope the subroutine with our:

lib/MyModule.rakumod

use v6.d;
unit module MyModule;

our sub hello () { say 'hello' }
#^
# \
#  globally scoped

main.raku

use v6.d;
# use lib './lib';
use module MyModule;

MyModule::hello();
#       ^^
#        \
#         namespace delimiter

You could export it instead:

lib/MyModule.rakumod

use v6.d;
unit MyModule;

#             mark for export
#            v-------v
sub hello () is export {
    say 'hello'
}

main.raku

use v6.d;
# use lib './lib';
use MyModule;

hello();

In addition to is export, there are other more fine grained ways to export.

I would recommend that if you are going to export, that you also make it global with our. That way if someone uses your module, but doesn't want to import your subs; they still have access to them.