Module All The Things!
META6::bin
what made think that he may not be alone. Further, customisation would required a fork what is less then ideal because one has to care a lot about upstream changes and may even have to cherry pick commits when going down that road.
That’s annoying and unneeded if bin/meta6
is turned into lib/META6/bin.pm6
. As it turns out that is surprisingly easy and already done.
I learned a few things I would like to share.
Firstly I wanted to provide the option to call a MAIN
just like any normal sub. Simply exporting them doesn’t work as they would be added as MAIN
candidates to the script sporting the use META6::bin
.
Lets have some code.
use v6.c; unit module was-a-main; our proto sub MAIN(|) is export(:MAIN) { * } multi sub MAIN(Int $a) { say "Int candidate"; } multi sub MAIN(Bool :$a) { say "bool candidate"; }
Fist we create a namespace we can refere to, both by putting the file into a directory and with the explicit unit module
statement. Then we export a proto as an our
sub with a tag called MAIN
. By providing the tag in use was-a-module :MAIN
we would pull all MAIN candidate into a script and they would be used as normal. Without the tag, the our
scope will allow to provide a FQN to call them as normal subs.
use v6.c; use was-a-main; was-a-main::MAIN(:a);
In META6::bin
I wanted to allow subs to be wrappable. To do so it is required to scope them with our
in the module and provide the FQN when wrapping.
use META6::bin :HELPER; &META6::bin::try-to-fetch-url.wrap({ say "checking URL: ⟨$_⟩"; callsame; }); META6::bin::MAIN(:check);
The sub try-to-fetch-url is used to check if URLs are accessible to catch typos in a META6.info
. By wrapping it one can make it verbose. Pretty much all subs are treated the same way, allowing to wrap to your heart’s content.
As melezhik has shown, there is more then one way to have a module created for you. Now it’s both easy and possible.
-
April 10, 2017 at 22:582017.15 Kaboom! ⁽¹⁾ | Weekly changes in and around Perl 6