in reply to How best to tell when my hash is "full" (all values defined)?

It seems to me that you only need data from the first three lines of the output from top. So why not just read those three lines and then exit the loop?

Also, I'd be more inclined to use a piped open and a while loop, rather than reading the entire output into an array. Especially as you are only using the first few lines.

Here is your script re-written slightly - the ouput appears to be the same as your original version. (Note - I didn't touch your pattern matches)

Update: whoops! In my enthusiasm to re-write your code, I forgot to address your main question. As TimToady pointed out, all you need to do is not predefine the hash keys, and then when you are done compare the number keys you have against the number you were expecting. Code updated to reflect that.

#!/usr/bin/perl -wl use strict; use Data::Dumper::Simple; my %stats; my $expected_keys = 5; my $top = "/usr/bin/top -b -n 1"; open(TOP, "$top|") or die "Cannot read top:$!"; while (my $line = <TOP>) { 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; last; } } print Dumper(%stats); my $num_keys = scalar keys %stats; if ($num_keys != $expected_keys) { print "Whoops! Expected $expected_keys keys, but I got $num_keys!" +; }

Output on my machine:

%stats = ( 'fmem' => '34048', 'tmem' => '775664', 'users' => '4', 'runproc' => '1', 'load' => '0.00' );

Hope this helps,
Darren :)