5 sub _clean_eval { eval $_[0] }
9 use Scalar::Util qw(weaken);
10 use base qw(Exporter);
12 our @EXPORT = qw(quote_sub unquote_sub quoted_from_sub);
19 my ($from, $captures, $indent) = @_;
24 or die "capture key should start with \@, \% or \$: $_";
25 (' ' x $indent).qq{my ${_} = ${1}{${from}->{${\perlstring $_}}};\n};
31 my ($code, $args, $extra, $local) = @_;
32 my $do = 'do { '.($extra||'');
33 if (my ($code_args, $body) = $code =~ / +my \(([^)]+)\) = \@_;(.*)$/s) {
34 if ($code_args eq $args) {
37 $do.'my ('.$code_args.') = ('.$args.'); '.$body.' }';
41 if ($local || $args ne '@_') {
42 $assign = ($local ? 'local ' : '').'@_ = ('.$args.'); ';
44 $do.$assign.$code.' }';
49 # HOLY DWIMMERY, BATMAN!
50 # $name => $code => \%captures => \%options
51 # $name => $code => \%captures
53 # $code => \%captures => \%options
56 (ref($_[-1]) eq 'HASH' and ref($_[-2]) eq 'HASH')
59 my $captures = pop if ref($_[-1]) eq 'HASH';
60 undef($captures) if $captures && !keys %$captures;
64 my $deferred = defer_sub +($options->{no_install} ? undef : $name) => sub {
65 unquote_sub($outstanding);
67 $outstanding = "$deferred";
68 $QUOTED{$outstanding} = [ $name, $code, $captures ];
69 weaken($WEAK_REFS{$outstanding} = $deferred);
75 $WEAK_REFS{$sub||''} and $QUOTED{$sub||''};
80 unless ($QUOTED{$sub}[3]) {
81 my ($name, $code, $captures) = @{$QUOTED{$sub}};
85 if (keys %$captures) {
86 $make_sub .= capture_unroll("\$_[1]", $captures, 2);
89 my $o_quoted = perlstring $sub;
92 # disable the 'variable $x will not stay shared' warning since
93 # we're not letting it escape from this scope anyway so there's
94 # nothing trying to share it
95 ? " no warnings 'closure';\n sub ${name} {\n"
96 : " \$Sub::Quote::QUOTED{${o_quoted}}[3] = sub {\n"
99 $make_sub .= " }".($name ? '' : ';')."\n";
101 $make_sub .= " \$Sub::Quote::QUOTED{${o_quoted}}[3] = \\&${name}\n";
103 $make_sub .= "}\n1;\n";
104 $ENV{SUB_QUOTE_DEBUG} && warn $make_sub;
108 local *{$name} if $name;
109 unless (_clean_eval $make_sub, $captures) {
110 die "Eval went very, very wrong:\n\n${make_sub}\n\n$@";
121 Sub::Quote - efficient generation of subroutines via string eval
127 use Sub::Quote qw(quote_sub unquote_sub quoted_from_sub);
129 quote_sub 'Silly::kitty', q{ print "meow" };
131 quote_sub 'Silly::doggy', q{ print "woof" };
135 quote_sub 'Silly::dagron',
136 q{ print ++$sound % 2 ? 'burninate' : 'roar' },
137 { '$sound' => \$sound };
143 Silly->dagron; # burninate
144 Silly->dagron; # roar
145 Silly->dagron; # burninate
149 This package provides performant ways to generate subroutines from strings.
155 my $coderef = quote_sub 'Foo::bar', q{ print $x++ . "\n" }, { '$x' => \0 };
157 Arguments: ?$name, $code, ?\%captures, ?\%options
159 C<$name> is the subroutine where the coderef will be installed.
161 C<$code> is a string that will be turned into code.
163 C<\%captures> is a hashref of variables that will be made available to the
164 code. See the L</SYNOPSIS>'s C<Silly::dagron> for an example using captures.
172 B<Boolean>. Set this option to not install the generated coderef into the
173 passed subroutine name on undefer.
179 my $coderef = unquote_sub $sub;
181 Forcibly replace subroutine with actual code.
183 If $sub is not a quoted sub, this is a no-op.
185 =head2 quoted_from_sub
187 my $data = quoted_from_sub $sub;
189 my ($name, $code, $captures, $compiled_sub) = @$data;
191 Returns original arguments to quote_sub, plus the compiled version if this
192 sub has already been unquoted.
194 Note that $sub can be either the original quoted version or the compiled
195 version for convenience.
199 my $prelude = capture_unroll '$captures', {
204 my $inlined_code = inlinify q{
207 print $x + $y . "\n";
208 }, '$x, $y', $prelude;
210 Takes a string of code, a string of arguments, a string of code which acts as a
211 "prelude", and a B<Boolean> representing whether or not to localize the
214 =head2 capture_unroll
216 my $prelude = capture_unroll '$captures', {
221 Arguments: $from, \%captures, $indent
223 Generates a snippet of code which is suitable to be used as a prelude for
224 L</inlinify>. C<$from> is a string will be used as a hashref in the resulting
225 code. The keys of C<%captures> are the names of the variables and the values
226 are ignored. C<$indent> is the number of spaces to indent the result by.
230 Much of this is just string-based code-generation, and as a result, a few caveats
235 Calling C<return> from a quote_sub'ed sub will not likely do what you intend.
236 Instead of returning from the code you defined in C<quote_sub>, it will return
237 from the overall function it is composited into.
241 quote_sub q{ return 1 if $condition; $morecode }
243 It might turn up in the intended context as follows:
249 return 1 if $condition;
256 Which will obviously return from foo, when all you meant to do was return from
257 the code context in quote_sub and proceed with running important code b.
261 Sub::Quote compiles quoted subs in an environment where C<< use strictures >>
262 is in effect. L<strictures> enables L<strict> and FATAL L<warnings>.
264 The following dies I<< Use of uninitialized value in print... >>
267 quote_sub 'Silly::kitty', q{ print undef };
269 If you need to disable parts of strictures, do it within the quoted sub:
271 quote_sub 'Silly::kitty', q{ no warnings; print undef };
275 See L<Moo> for support and contact informations.
279 See L<Moo> for authors.
281 =head1 COPYRIGHT AND LICENSE
283 See L<Moo> for the copyright and license.