brian d foy
brian d foy

Reputation: 132822

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

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.

Upvotes: 6

Views: 142

Answers (1)

Christoph
Christoph

Reputation: 169603

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 );

Upvotes: 7

Related Questions