tags:

views:

85

answers:

1

I am working so some stuffs where I need to get some information using kstat -p. So I am thinking to create a hash variable with all output of kstat -p.

Sample output from kstat -p

cpu_stat:0:cpu_stat0:user       18804249

To access values

@{$kstat->{cpu_stat}{0}{cpu_stat0}}{qw(user)};

I have also looked at CPAN for any available module and found Sun::Solaris::Kstat but that is not available with my Sun version. Please suggest code to create a hash variable with output values in kstat -p.

+6  A: 

With references, creating a hierarchical data structure is only slightly tricky; the only interesting part comes from the fact that we want to handle the final level differently (assigning a value instead of creating a new hash level).

# 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.
}
hobbs