In Modules§
See primary documentation in context for EXPORT
You can export arbitrary symbols with an EXPORT
sub. EXPORT
must return a Map
, where the keys are the symbol names and the values are the desired values. The names should include the sigil (if any) for the associated type.
# lib/MyModule.rakumodsub EXPORT
Which is going to be used from this main file:
# main.rakuuse lib 'lib';use MyModule;say ; # OUTPUT: «one»say ; # OUTPUT: «(one two three)»say ; # OUTPUT: «{one => two, three => four}»doit(); # OUTPUT: «Greetings from exported sub»say ShortName.new; # OUTPUT: «MyModule::Class.new»
Please note that EXPORT
can't be declared inside a package because it is part of the compunit rather than the package.
Whereas UNIT::EXPORT
packages deal with the named parameters passed to use
, the EXPORT
sub handles positional parameters. If you pass positional parameters to use
, they will be passed to EXPORT
. If a positional is passed, the module no longer exports default symbols. You may still import them explicitly by passing :DEFAULT
to use
along with your positional parameters.
# lib/MyModulesub EXPORT(?)sub always is export(:MANDATORY)#import with :ALL or :DEFAULT to getsub shy is export
Used from this main program
# main.rakuuse lib 'lib';use MyModule 'foo';say foo.new(); # OUTPUT: «MyModule::Class.new»always(); # OK - is importedshy(); # FAIL - «shy used at line 8. Did you mean 'say'?»
You can combine EXPORT
with type captures for interesting effect. This example creates a ?
postfix which will only work on Cool
s; please note that, by using $_
as an argument, we don't need to use a variable in the routine body and use just .so
, acting by default on the topic variable.
# lib/MakeQuestionable.rakumodsub EXPORT(::Questionable)
Which is used from here:
use lib 'lib';use MakeQuestionable Cool;say ( 0?, 1?, ?, %( a => "b" )? ).join(' '); # OUTPUT: «False True False True»