题
我的工作这么一些东西,我需要使用kstat -p
得到一些信息。所以我想创建具有kstat -p
的所有输出的散列变量。
Sample output from kstat -p
cpu_stat:0:cpu_stat0:user 18804249
要访问值
@{$kstat->{cpu_stat}{0}{cpu_stat0}}{qw(user)};
我也看了一下CPAN任何可用的模块,并发现Sun::Solaris::Kstat
但不可用我的Sun版本。请建议代码来创建与kstat -p
输出值的散列变量。
解决方案
使用参考文献,创建一个分层数据结构仅稍微棘手;唯一有趣的部分来自于我们要以不同方式处理最后一级(分配值,而不是创建一个新的哈希级)的事实。
# 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.
}
不隶属于 StackOverflow