更新时间:2023-02-14 11:00:03
sub to_nested_hash {
my $ref = \shift;
my $h = $$ref;
my $value = pop;
$ref = \$$ref->{ $_ } foreach @_;
$$ref = $value;
return $h;
}
说明:
我们知道:
my $h = {}; my $a = [];
).my $h = {}; my $a = [];
).这样做可能更明确:
foreach my $key ( @_ ) {
my $lvl = $$ref = {};
$ref = \$lvl->{ $key };
}
但由于重复使用这些参考习语,我完全照原样写了那行,并在发布前对其进行了测试,没有错误.
But owing to repeated use of these reference idioms, I wrote that line totally as it was and tested it before posting, without error.
至于替代方案,以下版本更容易"(想出来)
As for alternatives, the following version is "easier" (to think up)
sub to_nested_hash {
$_[0] //= {};
my $h = shift;
my $value = pop;
eval '$h'.(join '', map "->{\$_[$i]}", 0..$#_).' = $value';
return $h;
}
但大约慢 6-7 倍.
But about 6-7 times slower.