如何使用Perl使用kstat -p的输出创建哈希?

Spa*_*ace 0 perl sunos kstat

我正在做一些我需要获取一些信息的东西kstat -p.所以我想创建一个包含所有输出的哈希变量kstat -p.

Sample output from kstat -p

cpu_stat:0:cpu_stat0:user       18804249
Run Code Online (Sandbox Code Playgroud)

访问值

@{$kstat->{cpu_stat}{0}{cpu_stat0}}{qw(user)};
Run Code Online (Sandbox Code Playgroud)

我也查看过任何可用模块的CPAN,Sun::Solaris::Kstat但是我的Sun版本不提供.请建议使用输出值创建哈希变量的代码kstat -p.

hob*_*bbs 6

通过引用,创建分层数据结构只是有点棘手; 唯一有趣的部分来自于我们想要以不同方式处理最终级别的事实(分配值而不是创建新的哈希级别).

# 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.
}
Run Code Online (Sandbox Code Playgroud)