I create a hash with spaces for where I need information (just declare the keys with a slice). I then loop through some lines of data, parsing it out for the info I need. Generally, the data I need are near the beginning of the data, and I would like to escape from the loop as soon as I have the data I need, rather than after I've parsed all the lines. Here's what I have so far:
It just seems kind of clunky to me. That's partially because of the debugging output (it will eventually be silent--something like ($uds) || last; ). However, I'll probably want to do an additional check after the loop to make sure I didn't parse every single process and still come up empty on some of my stats due to (unexpected output from top|poorly formed REs).#get running processes, users, 1 min load average, total mem, free mem + (ultimately display free mem %) my @raw=`top -b -n 1`; my %stats; @stats{'users','load','tmem','fmem','runproc'} = (); my $its=0; foreach my $line (@raw){ if ($line =~ /up\s.+\s(\d+)\suser.+\s+load\saverage:\s+(\d+\.\d{2}), +/){ $stats{users}=$1; $stats{load}=$2; } elsif ($line =~ /(?:Tasks|processes):.+\s+(\d+) running/i){ $stats{runproc}=$1; } elsif ($line =~ /^Mem:\s+(\d+)k\s+(?:total|av),.+used,\s+(\d+)k\s+fr +ee/){ $stats{tmem}=$1; $stats{fmem}=$2; } $its++; my $uds=0; foreach (values(%stats)){ defined or ++$uds; } if ($uds){ print "Still $uds undefined values"; } else{ print "I'm done!"; last; } } ## end foreach my $line (@raw) print "I looped $its times to collect the data I need from $host";
Yes, I do know that "free" memory reported by top is not necessarily indicative of how much memory is available for new processes, due to buffering.
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |