use warnings; use strict; BEGIN { # closure: data in scope only to create_f() function my $common = 'fooble'; sub create_f { my ($user_source, # required: string: user source code ) = @_; my $private = 'xpto'; # ??? makes $common variable defined in eval ??? # any of these statements do the trick. # except as noted, tested in both 5.6.1 and 5.8.2 # print "in create_f(): common: $common \n"; # $common .= ''; map defined, $common; # note: not tested with 5.6.1 my $coderef = eval qq{ sub { $user_source } }; return $coderef; # code reference undefined if eval failed } } # end closure: create_f() function # NOTE: single quotes on here-doc tag below: no interpolation. my $function = create_f(<<'USER_CODE'); my $param = shift; print "param: $param common: $common private: $private \n"; return join ';', $param, $common, $private; USER_CODE my $freturn = $function->('hi there'); print "function return: `$freturn' \n";