I didn't expect that it's possible to dynamically access a lexical var by using eval within a closure-function (here "getset()"), but indeed it's possible.
There is no real need for this in Perl¹ ... but I wanted to share the insight I got! :)
# Eval in Closure # Accessing lexical by name? # use strict; sub alert { print @_,"\n"; } ; my $getset; my $change =sub { my $it=shift; $getset->($it,"post"); }; my $x="global"; my $test=sub { my $x="pre"; $getset=sub { my ($name,$val)=@_; eval('$'.$name."='".$val."'"); # I can access any variable in this + scope }; alert($x); # pre $change->("x"); alert($x); # post } ; $test->(); alert($x); # global
The motivation for this code is that in JS one can't pass simple data-types (i.e. "scalars") by reference one need to use objects instead.
But when converting Perl-code to JS one can't control potential aliasing/referencing of parameters, e.g. a called sub could assigning to $_[].
This functional pattern could be used as workaround, and works in both languages.
Cheers Rolf
¹) Hmm ...maybe as generic accessor method in OOP...
|
|---|