Modules: an introduction

Modules and how they work

N.B. "Module" is an overloaded term in Raku; this document focuses on use of the module declarator.

What are modules?

Modules, like classes and grammars, are a kind of package. Module objects are instances of the ModuleHOW metaclass; this provides certain capabilities useful for creating namespaces, versioning, delegation and data encapsulation (see also class and role).

To create a module, use the module declarator:

module M {}
    say M.HOW;   # OUTPUT: «Perl6::Metamodel::ModuleHOW.new␤»

Here we define a new module named M; introspection with HOW confirms that the metaclass underlying M is Perl6::Metamodel::ModuleHOW.

When to use modules

Modules are primarily useful for encapsulating code and data that do not belong inside a class or role definition. Module contents (classes, subroutines, variables, etc.) can be exported from a module with the is export trait; these are available in the caller's namespace once the module has been imported with import or use. A module can also selectively expose symbols within its namespace for qualified reference via our.

Working with modules

To illustrate module scoping and export rules, let's begin by defining a simple module M:

module M {
      sub greeting ($name = 'Camelia') { "Greetings, $name!" }
      our sub loud-greeting (--> Str)  { greeting().uc       }
      sub friendly-greeting is export  { greeting('friend')  }
    }

Recall that subroutines are lexically scoped unless otherwise specified (declarator sub is equivalent to my sub), so greeting in the above example is lexically scoped to the module and inaccessible outside of it. We've also defined loud-greeting with the our declarator, which means that in addition to being lexically scoped it is aliased in the module's symbol table. Finally, friendly-greeting is marked for export; it will be registered in the caller's symbol table when the module is imported:

import M;               # import the module
say M::loud-greeting;   # OUTPUT: «GREETINGS, CAMELIA!␤»
say friendly-greeting;  # OUTPUT: «Greetings, friend!␤»

Documentation about Modules

Want to distribute your modules?

See Also

Distributing modules: the configuration and structure

How to structure and configure Raku modules for distribution

Distributions: an introduction

Distributions and how they work

Distributions: testing

Testing your distribution of modules

Distributions: the tools

What can help you write/test/improve your distributions of modules

Distributions: uploading

How to upload your distribution to the ecosystem

Making modules: the code

How to organize your module with regard to its usage

Making modules: an introduction

Understanding modules

Using modules: the code

How to use Raku modules in your code

Using modules: finding and installing

How to find and install Raku modules

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.