Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Making lexically-scoped ref available to non-OO subs in another package

by wanna_code_perl (Pilgrim)
on Jul 12, 2013 at 12:41 UTC ( #1043960=perlquestion: print w/ replies, xml ) Need Help??
wanna_code_perl has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I'm going to try my best not to pose an XY Problem here, but I'm having a tough time coming up with a succinct explanation. Here goes nothing.

I'm working on initialization code for a complex system, with many user- (programmer-)defined levels of nested data structures. The data structure is trivial for a computer to traverse, but making it comprehensible to the programmer is another story. Further, trusting the programmer to initialize it correctly using pure Perl variable syntax would ask for a lot of artificial housekeeping and invite errors, or worse, ambiguity. Fortunately, implementing just a few new simple keywords solves all of these problems (many of them right at compile time) with simple, concise syntax, but having those subs operate on anything less than a file-scoped variable has eluded me. Here's what I've tried/considered:

  1. Pure-OO, using method calls in place of prototyped subs, but this is one of those rare cases where the prototypes are most of the benefit of the expanded syntax.
  2. I wrote a proof-of-concept that uses caller to work on a variable right in the calling namespace, but that's far too likely to cause subtle bugs if someone tries to do anything remotely complex with the initialization code.
  3. Package-scoped variable: In many ways, this is even worse, as it's now essentially a per-thread global for any of the operations.
  4. Closures: Even though the closures can easily be passed a reference and even planted into $caller::, they suffer the same problem as #2.
  5. Source filters: So far the best option, although I'd feel much better finding a simple solution with a little symbol table and prototype hacking, if such a solution exists.
  6. Text parsing: Parsing a scalar (re-inventing Perl, inventing something even more arbitrary, or trying to stuff this problem into a well-known format), would definitely be an anti-pattern in this case, IMO.

Here's the sort of syntax I'm aiming for:

use The::Package; # sub my_generator(&) is exported by The::Package my $complex_result = my_generator { foo 'bar'; takes_coderef { ... }; }; foo 'baz'; # Should not affect $complex_result. # Ideally, should croak, or not even compile.

I hope this question makes sense, and has a solution which is much simpler than my explanation. The short, short version of my question is: is there any way to implement prototyped subs that will automatically gain access to a given scalar/ref/object/alias to the same without explicitly passing it in to every call or using the $arrow->notation?)

Comment on Making lexically-scoped ref available to non-OO subs in another package
Select or Download Code
Re: Making lexically-scoped ref available to non-OO subs in another package
by tobyink (Abbot) on Jul 12, 2013 at 12:53 UTC

    This seems to work fine for me:

    #!/usr/bin/env perl use v5.14; package The::Package { use Carp; use base "Exporter"; BEGIN { our @EXPORT = qw( my_generator foo takes_coderef ) }; my $scratchpad; sub my_generator (&) { $scratchpad = {}; shift->(); my $tmp = $scratchpad; undef $scratchpad; return $tmp; } sub foo ($) { croak "foo must be called within my_generator" unless $scratch +pad; $scratchpad->{foo} = shift; } sub takes_coderef (&) { croak "takes_coderef must be called within my_generator" unles +s $scratchpad; $scratchpad->{coderef} = shift; } BEGIN { $INC{"The/Package.pm"} = __FILE__ }; }; use The::Package; use Data::Dumper; my $complex_result = my_generator { foo 'bar'; takes_coderef { ... }; }; print Dumper($complex_result); foo 'baz'; # Should not affect $complex_result. # Ideally, should croak, or not even compile.

    If you want to be able to nest calls to my_generator then you need to have a stack of scratchpads, but that's very little extra work.

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
      package The::Package { use Carp; use base "Exporter"; BEGIN { our @EXPORT = qw( my_generator foo takes_coderef ) }; my $scratchpad; sub my_generator (&) { $scratchpad = {}; shift->(); my $tmp = $scratchpad; undef $scratchpad; return $tmp; }

      Just when I thought I was getting the hang of Perl..! I had no idea a my package variable would work like this.

      I'm amazed at the elegance of this, and that you came up with this rather instantaneously. Thank you!

        I probably wouldn't have come up with it so quickly if I hadn't been playing around with p5-mop-redux which is a prototype of a hopefully future Perl core feature. The prototype uses rather a similar technique (combined with lots of Devel::Declare magic) to provide its class-building syntax, though it uses localized package variables rather than lexicals.

        (I've also done something fairly similar in Smart::Dispatch.)

        package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
Re: Making lexically-scoped ref available to non-OO subs in another package
by Anonymous Monk on Jul 12, 2013 at 13:25 UTC

    Have you heard of local? See source of Web::Scraper, the jist of which is

    sub my_outer(&) { my( $callback ) = @_; my $stash = {}; no warnings 'redefine'; ## closure local *my_inners = sub { ... $stash ... }; local *foo = sub { ... $stash ... }; local *result = sub { ... $stash ... }; return $callback->( $stash ); }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1043960]
Approved by tobyink
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (12)
As of 2014-07-28 17:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (204 votes), past polls