Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I export a LEAVE phaser to the outer scope of a use statement

Tags:

raku

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?

like image 1000
Elizabeth Mattijsen Avatar asked Jun 13 '18 19:06

Elizabeth Mattijsen


2 Answers

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.

like image 177
Elizabeth Mattijsen Avatar answered Nov 19 '22 01:11

Elizabeth Mattijsen


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...

like image 1
Robert Lemmen Avatar answered Nov 19 '22 01:11

Robert Lemmen