Zysys Perl6 Tutorials

These Perl6 Tutorials exist when we are writing some code, find an issue, and solve it. Usually it is an implementation issue. This documents those issues.

Modular Code

It is best to modularize long code that has distinct parts. The problem that arises is when those parts are related and need to interact.

This problem arose when writing a single object oriented interface to a set of modules that need to be able to interact with one another.

Here's how to do it:

Put the modules you require underneath the module MODULE; declaration. In the used module, make sure to use is export on the subs you require.

Think of each sub SUBROUTINE is export as a private backend function that can be passed between modules. Use a wrapper class or another subroutine as an API for the backend subs so the main program isn't overwhelmed with use statements and only has access to things it should have access to (as opposed to things that only the backend should have access to).

Example:

test.pl6:

#!/usr/bin/perl6

use v6;
use Test::ClassTest;

my $t = ClassTest.new();
$t.hi();

Test/ClassTest.pm6:

#!/usr/bin/perl6

use v6;
module Test::ClassTest;
use Test::ClassTest;

class ClassTest is export {
    method hi { hi(); } # From Test::ClassTest_Two
}

Test/ClassTest_Two.pm6:

#!/usr/bin/perl6

use v6;
module Test::ClassTest_Two;

sub hi() is export {
    say 'hi';
}

You can run this code with perl6 -I . test.pl6

Comments

Topic revision: r1 - 2014-12-14 - ZachBornheimer
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2021 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback