【发布时间】:2010-01-19 15:25:47
【问题描述】:
我正在使用配置文件(在 YAML 中)定义类型,这些类型稍后用于验证我的应用所需的其他配置值:
---
action: >
use List::MoreUtils;
my $value = $_;
any { $value eq $_ } qw(fatal keep merge non-fatal replace);
dir : return defined $_ ? -d $_ : -1;
file : return defined $_ ? -f $_ : -1;
string: 1;
---
config-element:
value: foo
type : file
etc ...
思路是把eval每个类型定义,扔进一个hash,然后调用验证配置数据(下面是示意图,方便理解):
#throw sub refs into hash
my %type_sub;
foreach my $key (keys %$type_def_ref) {
my $sub_str = "sub {$type_def_ref->{$key}}";
$type_sub{$key} = eval $sub_str;
}
#validate (myfile is a real file in the cwd)
print $type_sub{file}->('myfile'),"\n";
print $type_sub{action}->('fatal'), "\n";
问题在于 %type_sub 中的子例程似乎不接受参数。在上述情况下,第一个打印语句输出-1,而第二个输出:
Use of uninitialized value $value in string eq at (eval 15) line 1.
Use of uninitialized value $_ in string eq at (eval 15) line 1.
Can't call method "any" without a package or object reference at
(eval 15) line 1.
这根本不是我所期望的,但是子程序正在被调用。
我做错了什么?
编辑: 我当时很马虎,现在一切正常。感谢弗里多。
【问题讨论】:
标签: perl parameters eval subroutine