PrePAN

Sign in to PrePAN

Sub::QuoteX::Utils Sugar for Sub::Quote

Good

Synopsis

use Sub::Quote;
use Sub::QuoteX::Utils qw[ quote_subs ];

my $sub;

# class with method
{
    package Yipee;
    use Moo;
    sub halloo { shift; print "Yipee, @_\n" }
}

# and the object
my $object = Yipee->new;

# quoted sub
my $foo = quote_sub(
  q[ print "$foo: @_\n"],
  { '$foo' => \"Foo" }
);


# bare sub
sub bar { print "Bar: @_\n" }


# create single subroutine. each invoked piece of code will have a
# localized view of @_
$sub = quote_subs(
    \&bar,                             # bare sub
    $foo,                              # quoted sub
    [ q[ print "$goo: @_\n"],          # code in string with capture
      capture => { '$goo' => \"Goo" },
    ],
    [ $object, 'halloo' ],             # method call
);


# and run it
$sub->( "Common" );

# Bar: Common
# Goo: Common
# Foo: Common
# Yipee: Common


# now, give each a personalized @_
$sub            = quote_subs(
    [ \&bar,                           # bare sub
      args      => [qw( Bar )]
    ],
    [ $foo,                            # quoted sub
      args      => [qw( Foo )]
    ],
    [ q[ print "$goo, @_\n"],          # code in string with capture
      capture => { '$goo' => \"Goo" },
      args    => [qw( Goo )],
    ],
    [ $object, 'halloo',               # method call
        args    => [qw( Yipee )]
    ],
);

$sub->( "Common" );

# Bar: Bar
# Foo: Foo
# Goo: Goo
# Yipee: Yipee

# now, explicitly empty @_
$sub = quote_subs(
    [ \&bar,                           # bare sub
      args => undef
    ],
    [ $foo,                            # quoted sub
      args => undef
    ],
    [ q[ print "$goo, @_\n"],          # code in string with capture
      capture => { '$goo' => \"Goo" },
      args    => undef,
    ],
    [ $object, 'halloo',               #method call
      args => undef
    ],
);

$sub->( "Common" );

# Bar:
# Foo:
# Goo:
# Yipee:

Description

Sub::QuoteX::Utils provides a simplified interface to the process of combining Sub::Quote compatible code references with new code.

Sub::Quote provides a number of routines to make code more performant by inlining separate chunks of code into a single compiled subroutine.

When a chunk of code is compiled into a subroutine by Sub::Quote::quote_sub(), Sub::Quote keeps track of the code and any captured variables used to construct that subroutine, so that new code can be added to the original code and the results compiled into a new subroutine.

Sub::QuoteX::Utils makes that latter process a little easier.

Comments

Please sign up to post a review.