Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare and use a Perl 6 module in the same file as the program?

Tags:

module

raku

Sometimes I don't want multiples files, especially if I'm playing around with an idea that I want to keep a nice structure that can turn into something later. I'd like to do something like this:

module Foo {
    sub foo ( Int:D $number ) is export {
        say "In Foo";
        }
    }

foo( 137 );

Running this, I get a compilation error (which I think is a bit odd for a dynamic language):

===SORRY!=== Error while compiling /Users/brian/Desktop/multi.pl
Undeclared routine:
    foo used at line 9

Reading the Perl 6 "Modules" documentation, I don't see any way to do this since the various verbs want to look in a particular file.

like image 711
brian d foy Avatar asked Jan 09 '16 01:01

brian d foy


1 Answers

Subroutine declarations are lexical, so &foo is invisible outside of the module's body. You need to add an import statement to the mainline code to make it visible:

module Foo {
    sub foo ( Int:D $number ) is export { ... }
}

import Foo;
foo( 137 );

Just for the record, you could also manually declare a &foo variable in the mainline and assign to that from within the module:

my &foo;

module Foo {
    sub foo ( Int:D $number ) { ... } # no export necessary

    &OUTER::foo = &foo;
}

foo( 137 );
like image 75
Christoph Avatar answered Nov 15 '22 09:11

Christoph