1 package Eval::WithLexicals::Role::Eval;
5 has lexicals => (is => 'rw', default => quote_sub q{ {} });
8 my %valid_contexts = map +($_ => 1), qw(list scalar void);
11 is => 'rw', default => quote_sub(q{ 'list' }),
14 die "Invalid context type $val - should be list, scalar or void"
15 unless $valid_contexts{$val};
21 is => 'rw', default => quote_sub q{ 'Eval::WithLexicals::Scratchpad' }
25 is => 'rw', default => quote_sub q{ 'use strictures 1;' }
31 return Sub::Quote::capture_unroll('$_[2]', $self->lexicals, 2);
35 ( qq{ BEGIN { Eval::WithLexicals::Util::capture_list() } } )
39 my ($self, $to_eval) = @_;
40 local *Eval::WithLexicals::Cage::current_line;
41 local *Eval::WithLexicals::Cage::pad_capture;
42 local *Eval::WithLexicals::Cage::grab_captures;
44 my $package = $self->in_package;
45 my $setup_code = join '', $self->setup_code;
46 my $capture_code = join '', $self->capture_code;
48 local our $current_code = qq!
50 sub Eval::WithLexicals::Cage::current_line {
54 ;sub Eval::WithLexicals::Cage::pad_capture { }
56 sub Eval::WithLexicals::Cage::grab_captures {
57 no warnings 'closure'; no strict 'vars';
58 package Eval::WithLexicals::VarScope;!;
59 # rest is appended by Eval::WithLexicals::Util::capture_list, called
60 # during parsing by the BEGIN block from capture_code.
62 $self->_eval_do(\$current_code, $self->lexicals, $to_eval);
63 $self->_run(\&Eval::WithLexicals::Cage::current_line);
67 my($self, $code) = @_;
70 my $ctx = $self->context;
73 } elsif ($ctx eq 'scalar') {
80 %{$self->_grab_captures},
87 my $cap = Eval::WithLexicals::Cage::grab_captures();
88 foreach my $key (keys %$cap) {
89 my ($sigil, $name) = $key =~ /^(.)(.+)$/;
90 my $var_scope_name = $sigil.'Eval::WithLexicals::VarScope::'.$name;
91 if ($cap->{$key} eq eval "\\${var_scope_name}") {
99 my ($self, $text_ref, $lexical, $original) = @_;
101 if ($_[1] eq '/eval_do') {
102 open my $fh, '<', $text_ref;
108 do '/eval_do' or die $@;
112 package Eval::WithLexicals::Util;
114 use B qw(svref_2object);
117 my $pad_capture = \&Eval::WithLexicals::Cage::pad_capture;
118 my @names = grep $_ ne '&', map $_->PV, grep $_->isa('B::PV'),
119 svref_2object($pad_capture)->OUTSIDE->PADLIST->ARRAYelt(0)->ARRAY;
120 $Eval::WithLexicals::Role::Eval::current_code .=
121 '+{ '.join(', ', map "'$_' => \\$_", @names).' };'