【发布时间】:2019-02-26 23:33:35
【问题描述】:
我有一个大型多维散列,它是 JSON 结构的导入。
my %bighash;
%bighash 中有一个元素叫做:
$bighash{'core'}{'dates'}{'year'} = 2019.
我有一个名为 core.dates.year 的单独字符串变量,我想用它从 %bighash 中提取 2019。
我已经写了这段代码:
my @keys = split(/\./, 'core.dates.year');
my %hash = ();
my $hash_ref = \%hash;
for my $key ( @keys ){
$hash_ref->{$key} = {};
$hash_ref = $hash_ref->{$key};
}
当我执行时:
say Dumper \%hash;
输出:
$VAR1 = {
'core' => {
'dates' => {
'year' => {}
}
}
};
到目前为止一切顺利。但我现在想做的是:
print $bighash{\%hash};
我想返回 2019。但是没有返回任何内容,或者我看到有关“在连接 (.) 或 script.pl 第 1371 行第 17 行的字符串中使用未初始化值的错误(#1 )...
有人能告诉我发生了什么吗?
我的项目涉及将字符串嵌入到外部文件中,然后将其替换为 %bighash 中的实际值,因此它只是字符串插值。
谢谢!
【问题讨论】:
-
我在回答中加入了更快、更简单的 Data::Diver 的
Dive和DiveVal版本。