4 use Sub::Exporter -setup => {
5 exports => [qw(eval_closure)],
6 groups => { default => [qw(eval_closure)] },
8 # ABSTRACT: safely and cleanly create closures via string eval
12 use Scalar::Util qw(reftype);
19 my $code = eval_closure(
20 source => 'sub { $foo++ }',
29 my $code2 = eval_closure(
30 source => 'sub { $code->() }',
31 ); # dies, $code isn't in scope
35 String eval is often used for dynamic code generation. For instance, C<Moose>
36 uses it heavily, to generate inlined versions of accessors and constructors,
37 which speeds code up at runtime by a significant amount. String eval is not
38 without its issues however - it's difficult to control the scope it's used in
39 (which determines which variables are in scope inside the eval), and it can be
40 quite slow, especially if doing a large number of evals.
42 This module attempts to solve both of those problems. It provides an
43 C<eval_closure> function, which evals a string in a clean environment, other
44 than a fixed list of specified variables. It also caches the result of the
45 eval, so that doing repeated evals of the same source, even with a different
46 environment, will be much faster (but note that the description is part of the
47 string to be evaled, so it must also be the same (or non-existent) if caching
52 =func eval_closure(%args)
54 This function provides the main functionality of this module. It is exported by
55 default. It takes a hash of parameters, with these keys being valid:
61 The string to be evaled. It should end by returning a code reference. It can
62 access any variable declared in the C<environment> parameter (and only those
63 variables). It can be either a string, or an arrayref of lines (which will be
64 joined with newlines to produce the string).
68 The environment to provide to the eval. This should be a hashref, mapping
69 variable names (including sigils) to references of the appropriate type. For
70 instance, a valid value for environment would be C<< { '@foo' => [] } >> (which
71 would allow the generated function to use an array named C<@foo>). Generally,
72 this is used to allow the generated function to access externally defined
73 variables (so you would pass in a reference to a variable that already exists).
77 This lets you provide a bit more information in backtraces. Normally, when a
78 function that was generated through string eval is called, that stack frame
79 will show up as "(eval n)", where 'n' is a sequential identifier for every
80 string eval that has happened so far in the program. Passing a C<description>
81 parameter lets you override that to something more useful (for instance,
82 L<Moose> overrides the description for accessors to something like "accessor
83 foo at MyClass.pm, line 123").
87 This lets you override the particular line number that appears in backtraces,
88 much like the C<description> option. The default is 1.
92 Normally, this function appends the source code that failed to compile, and
93 prepends some explanatory text. Setting this option to true suppresses that
94 behavior so you get only the compilation error that Perl actually reported.
103 $args{source} = _canonicalize_source($args{source});
104 _validate_env($args{environment} ||= {});
106 $args{source} = _line_directive(@args{qw(line description)})
108 if defined $args{description} && !($^P & 0x10);
110 my ($code, $e) = _clean_eval_closure(@args{qw(source environment)});
113 if ($args{terse_error}) {
117 croak("Failed to compile source: $e\n\nsource:\n$args{source}")
124 sub _canonicalize_source {
127 if (defined($source)) {
129 if (reftype($source) eq 'ARRAY'
130 || overload::Method($source, '@{}')) {
131 return join "\n", @$source;
133 elsif (overload::Method($source, '""')) {
137 croak("The 'source' parameter to eval_closure must be a "
138 . "string or array reference");
146 croak("The 'source' parameter to eval_closure is required");
153 croak("The 'environment' parameter must be a hashref")
154 unless reftype($env) eq 'HASH';
156 for my $var (keys %$env) {
157 croak("Environment key '$var' should start with \@, \%, or \$")
158 unless $var =~ /^([\@\%\$])/;
159 croak("Environment values must be references, not $env->{$var}")
160 unless ref($env->{$var});
164 sub _line_directive {
165 my ($line, $description) = @_;
167 $line = 1 unless defined($line);
169 return qq{#line $line "$description"\n};
172 sub _clean_eval_closure {
173 my ($source, $captures) = @_;
175 if ($ENV{EVAL_CLOSURE_PRINT_SOURCE}) {
176 _dump_source(_make_compiler_source(@_));
179 my @capture_keys = sort keys %$captures;
180 my ($compiler, $e) = _make_compiler($source, @capture_keys);
182 if (defined $compiler) {
183 $code = $compiler->(@$captures{@capture_keys});
186 if (defined($code) && (!ref($code) || ref($code) ne 'CODE')) {
187 $e = "The 'source' parameter must return a subroutine reference, "
199 my $source = _make_compiler_source(@_);
201 unless (exists $compiler_cache{$source}) {
204 my $compiler = eval $source;
206 $compiler_cache{$source} = [ $compiler, $e ];
209 return @{ $compiler_cache{$source} };
213 sub _make_compiler_source {
214 my ($source, @capture_keys) = @_;
219 'my ' . $_ . ' = ' . substr($_, 0, 1) . '{$_[' . $i++ . ']};'
230 if (try { require Perl::Tidy }) {
231 Perl::Tidy::perltidy(
233 destination => \$output,
248 Please report any bugs through RT: email
249 C<bug-eval-closure at rt.cpan.org>, or browse to
250 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Eval-Closure>.
256 =item * L<Class::MOP::Method::Accessor>
258 This module is a factoring out of code that used to live here
264 You can find this documentation for this module with the perldoc command.
266 perldoc Eval::Closure
268 You can also look for information at:
272 =item * AnnoCPAN: Annotated CPAN documentation
274 L<http://annocpan.org/dist/Eval-Closure>
278 L<http://cpanratings.perl.org/d/Eval-Closure>
280 =item * RT: CPAN's request tracker
282 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Eval-Closure>
286 L<http://search.cpan.org/dist/Eval-Closure>
292 Jesse Luehrs <doy at tozt dot net>
294 Based on code from L<Class::MOP::Method::Accessor>, by Stevan Little and the