Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
go ahead... be a heretic
 
PerlMonks  

Re: Module to parse output from Unix ps command?

by hdb (Parson)
on Apr 10, 2013 at 20:12 UTC ( #1028034=note: print w/ replies, xml ) Need Help??


in reply to Module to parse output from Unix ps command?

It was easier said than done...

use strict; use warnings; use Data::Dumper; my $command = "ps -f"; my $id = "PID"; my @ps =`$command`; $ps[0] =~ s/^\s*//; my @header = split /\s+/, shift @ps; my ($posid) = grep { $header[$_] eq $id } 0..$#header; die "$id: No such column!\n" unless defined( $posid ); splice @header, $posid, 1; my $n = (scalar @header) - 1; my %psdata; while( @ps ) { my $row = shift @ps; $row =~ s/^\s*//; my @row = split /\s+/, $row; my $this_id = splice @row, $posid, 1; @{$psdata{$this_id}}{@header[0..$n-1]} = splice @row, 0, $n; $psdata{$this_id}{$header[$n]} = join " ", @row; # inaccurate as it +just pastes everything together } print Dumper( %psdata );


Comment on Re: Module to parse output from Unix ps command?
Download Code
Re^2: Module to parse output from Unix ps command?
by Krambambuli (Deacon) on Apr 11, 2013 at 10:47 UTC
    Using split's third possible argument too instead of just /\s+/, you'd preserve the original spacing of the user command as well (assuming it's always the last column).


    Krambambuli
    ---

      Thanks for this comment, I never heard about this third argument. Here is the updated script:

      use strict; use warnings; use Data::Dumper; my $command = "ps -f"; my $id = "PID"; my @ps =`$command`; $ps[0] =~ s/^\s*//; my @header = split /\s+/, shift @ps; my ($posid) = grep { $header[$_] eq $id } 0..$#header; die "$id: No such column!\n" unless defined( $posid ); splice @header, $posid, 1; my %psdata; while( @ps ) { my $row = shift @ps; chomp $row; $row =~ s/^\s*//; my @row = split /\s+/, $row, $#header+2; my $this_id = splice @row, $posid, 1; @{$psdata{$this_id}}{@header} = @row; } print Dumper( %psdata );

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1028034]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (11)
As of 2014-04-16 21:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (434 votes), past polls