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];
56 if ($ENV{EVAL_CLOSURE_PRINT_SOURCE}) {
57 _dump_source(_make_source(@_), $_[2]);
60 my $code = eval _make_source(@_);
65 my ($source, $__captures) = @_;
68 die "Capture key should start with \@, \% or \$: $_"
70 'my ' . $_ . ' = ' . $1 . '{$__captures->{\'' . $_ . '\'}};';
77 my ($source, $name) = @_;
80 if (try { require Perl::Tidy }) {
83 destination => \$output,
90 $name = defined($name) ? $name : "__ANON__";
91 warn $name . ":\n" . $output . "\n";