0

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
Space
  • 7,049
  • 6
  • 49
  • 68
  • 2
    Sun::Solaris::Kstat doesn't seem to exist. Solaris::Kstat does, though. Why don't you simply install that? – innaM Nov 25 '09 at 10:31
  • 2
    The data structure you are trying to create looks rather strange. You want an array at the top level? And what is qw(user) supposed to do? – innaM Nov 25 '09 at 10:32
  • 3
    Finally, what exactly is your problem? Do you need help parsing the output of kstat? Or do you need help creating that data stucture? – innaM Nov 25 '09 at 10:33
  • @Manni: 1) I don't have permissions to install any perl modules on this system. 2)yes and qw is to use other values like qw(user kernal iowait) 3) I need help to create a data structure and to access values based on the options provided as given in my option to access values. – Space Nov 25 '09 at 11:04
  • 4
    You don't need permission to install Perl modules. See, e.g., here: http://stackoverflow.com/questions/540640/how-can-i-install-a-cpan-module-into-a-local-directory – innaM Nov 25 '09 at 11:32
  • 1
    @Manni: I will do that if i can but Solaris::Kstat module in CPAN this only supports Solaris 2.5.1, 2.6 & 2.7 and I have version 5.10 – Space Nov 25 '09 at 11:40

1 Answers1

6

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
  • 223,387
  • 19
  • 210
  • 288