in reply to Accessing lexicals in other scopes dynamically by name
I didn't expect that it's possible to dynamically access a lexical var by using eval
It would be a bit silly if one couldn't do
my $greet = "Hello World"; eval ' print "$greet\n"; ';
eval doesn't know how its argument was generated, so
andeval 'print "$gr' . 'eet\n";';
are both equivalent to the first.my $name = $greet; eval 'print "$' . $name . '\n";';
Note: Subs only capture variables it knows it will need.
$ perl -E' use warnings; use strict; sub f { my $n="ok"; sub { eval q{$n} } } say f->() ' Variable "$n" is not available at (eval 1) line 2. Use of uninitialized value in say at -e line 4. $ perl -E' use warnings; use strict; sub f { my $n="ok"; sub { $n; eval q{$n} } } say f->() ' Useless use of private variable in void context at -e line 3. ok $ perl -E' use warnings; use strict; sub f { my $n="ok"; sub { $n if 0; eval q{$n} } } say f->() ' ok
|
|---|