For that matter, you could just do it like this (adding the suggestion from another reply below):
my %stats;
open(TOP, "top -b -n 1 |");
my $ndone = 0;
while (<TOP>) {
if ( /up\s.+\s(\d+)\suser.+\s+load\saverage:\s+(\d+\.\d{2}),/ ){
$stats{users}=$1;
$stats{load}=$2;
$ndone +=2;
}
elsif ( /(?:Tasks|processes):.+\s+(\d+) running/i ){
$stats{runproc}=$1;
$ndone++;
}
elsif ( /^Mem:\s+(\d+)k\s+(?:total|av),.+used,\s+(\d+)k\s+free/ ){
$stats{tmem}=$1;
$stats{fmem}=$2;
$ndone += 2;
}
last if ( $ndone == 5 );
}
if ( $ndone < 5 ) {
warn "I only got $ndone factoids from top. Bummer.\n";
}
else {
print "I got everything in just $. lines of input.\n";
}
|