📘 The require keyword to use a module in Perl 6

The require keyword loads a module at a runtime unlike the use, which loads it at the compile-time.

For example, here is a module with a single sub, which returns the sum of its arguments.

unit module Math; 

our sub sum(*@a) {
    return [+] @a;
}

(The star in *@a is required to tell Perl to pack all the arguments into a single array so that we can call the sub as sum(1, 2, 3). With no *, a syntax error will occur, as the sub expects an array but not three scalars.)

Now, require the module and use its sub.

require Math; 

say Math::sum(24..42); # 627

Before the import Math instruction, the programme will not be able to call Math::sum() because the name is not yet known. A single import Math; will not help as the import happens at compile-time when the module is not loaded yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s