I want to create a Perl 6 module that would "export" a LEAVE
phaser to the scope in which the use
statement is placed. I have not found a way to do that.
I assume this would need to be done inside an EXPORT
sub, but how? The default functionality of an EXPORT
sub is to just return a Map
with name => object mapping of things to export. As far as I know, there's no way to introspect what the outer scope is. Or am I missing something?
Thanks to Zoffix++ for pointing out a very hacky way of doing this.
sub EXPORT() {
$*W.add_phaser: $*LANG, 'LEAVE', { code you want to run }
{} # need to show that we're not exporting anything
}
This hack depends on various Rakudo internals, and is therefore not recommended to be used "in the wild". And it's quite likely that a better, more supportable way will be implemented for this functionality in the near future.
This hack was needed for a module that supports a sort of timely destruction other than from the direct scope in which an object is created (aka LEAVE
phaser). This is typically handled in Perl 5 by using reference counting and calling DESTROY
if the reference count of an object goes to 0.
This module can now be found in the Perl 6 ecosystem: FINALIZER. This module allows module developers to mark created objects for finalization: by default on program exit. Or from a scope indicated by the client program.
Not sure this is possible, but other people might know more. But what are you after anyway? I had a similar desire a while ago, I wanted to do something like a RAII lock. I solved it by wrapping the block rather than putting the LEAVE into it directly:
sub mtest($block) { LEAVE { say "hoo" }; $block() }
mtest { say "woo"; }
Perhaps that works for you as well...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With