在 Perl 评估中捕获变量赋值 [英] Capture variable assignments in a Perl eval
问题描述
我希望能够从 Perl 评估中捕获变量分配.也就是说,确定代码中分配了哪些变量名并提取它们的值.
I would like to be able to capture variable assignments from a Perl eval. That is, to determine what variable names have been assigned to within the code and extract their value.
例如,如果我运行:
eval '$foo=42; $bar=3.14;'
eval 的结果是 3.14(评估的最后一个值),但我也希望能够确定名称$foo"和$bar"及其值(事先不知道名称).
The result of the eval is 3.14 (the last value evaluated), but I would also like to be able to determine the names "$foo" and "$bar" and their values (without knowing the names in advance).
我已经阅读了几种将变量插入到 eval 块中的方法,通过 Safe 和 Eval::Context,但还没有任何提取它们的方法.我更熟悉 Python 的 eval/exec,它内置了对此的支持.
I have read up on a couple of ways of inserting variables into the eval block, through Safe and Eval::Context, but not yet any way of extracting them. I am more familiar with Python's eval/exec which have built in support for this.
推荐答案
这是我尝试根据 安全,正如埃里克·斯特罗姆 (Eric Strom) 所建议的那样.
Here's my attempt at fleshing out a solution based on Safe, as suggested by Eric Strom.
package main;
use warnings; use strict;
use Safe;
my $cpt = new Safe;
$cpt->permit_only(qw(sassign lineseq padany const rv2sv leaveeval));
my $name_space = $cpt->root;
my $no_strict = 0;
#
# populate the clean symbol table
#
$cpt->reval('0');
die "safe compartment initialisation error: $@" if $@;
my %symtab_clean = do {no strict 'refs'; %{$name_space.'::'} };
my $result = $cpt->reval('$foo=42; $bar=3.14;', $no_strict);
if ($@) {
warn "eval error: $@";
}
else {
#
# symbol table additions
#
my %symtab_dirty = do {no strict 'refs'; %{$name_space.'::'} };
my @updated_variables = grep { ! exists $symtab_clean{$_} } (sort keys %symtab_dirty);
foreach my $variable (@updated_variables) {
my $value = do{ no strict 'refs'; ${$name_space.'::'.$variable} };
print "variable $variable was set to: $value\n"
}
}
注意事项:
- 以上允许最小限制的 saf 操作码集.请参阅 perl 操作码
- 我选择在执行命令之前和之后寻找差异
这篇关于在 Perl 评估中捕获变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!