2 use Sub::Exporter -setup => {
3 exports => [qw(eval_closure)],
8 use Scalar::Util qw(reftype);
13 $args{source} = _canonicalize_source($args{source});
15 my ($code, $e) = _clean_eval_closure(@args{qw(source environment name)});
17 croak("Failed to compile source: $e\n\nsource:\n$args{source}")
23 sub _canonicalize_source {
26 if (defined($source)) {
28 if (reftype($source) eq 'ARRAY'
29 || overload::Method($source, '@{}')) {
30 return join "\n", @$source;
32 elsif (overload::Method($source, '""')) {
36 croak("The 'source' parameter to eval_closure must be a "
37 . "string or array reference");
45 croak("The 'source' parameter to eval_closure is required");
49 sub _clean_eval_closure {
50 # my ($source, $__captures, $name) = @_
51 my $__captures = $_[1];
57 if ($ENV{EVAL_CLOSURE_PRINT_SOURCE}) {
58 _dump_source(_make_source(@_), $_[2]);
61 my $code = eval _make_source(@_);
67 my ($source, $__captures) = @_;
70 die "Capture key should start with \@, \% or \$: $_"
72 'my ' . $_ . ' = ' . $1 . '{$__captures->{\'' . $_ . '\'}};';
79 my ($source, $name) = @_;
82 if (try { require Perl::Tidy }) {
85 destination => \$output,
92 $name = defined($name) ? $name : "__ANON__";
93 warn $name . ":\n" . $output . "\n";