使用引用,创建分层数据结构只是有点棘手;唯一有趣的部分来自我们希望以不同方式处理最终级别的事实(分配一个值而不是创建一个新的哈希级别)。
# If you don't create the ref here then assigning $target won't do
# anything useful later on.
my $kstat = {};
open my $fh, '-|', qw(kstat -p) or die "$! execing kstat";
while (<$fh>) {
chomp;
my ($compound_key, $value) = split " ", $_, 2;
my @hier = split /:/, $compound_key;
my $last_key = pop @hier; # handle this one differently.
my $target = $kstat;
for my $key (@hier) { # All intermediate levels
# Drill down to the next level, creating it if we have to.
$target = ($target->{$key} ||= {});
}
$target->{$last_key} = $value; # Then write the final value in place.
}