Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort hash of hashes by values

Status
Not open for further replies.

BrianAtWork

Programmer
Apr 12, 2004
148
US
Maybe I'm going about this the wrong way, but here's what I'm trying to do:

I have a hash that is storing the output from the unix "df" command, to get the disk used and disk free for each filesystem. Here is how I build the hash:
Code:
sub get_df {
    my %hash=();
    my @data=qx(df -t -k);
    chomp(@data);
    foreach (@data){
        next if (/^Filesystem/);
        my @parts=split(' ',$_);
        next unless ($parts[2] =~/\d+/ && $parts[3] =~/\d+/);
        $hash{$parts[5]}{"used"}=$parts[2];
        $hash{$parts[5]}{"free"}=$parts[3];
        $hash{$parts[5]}{"pused"}=$parts[4];
    }#end foreach
    return %hash;
}

#sample output from the df -t -k:
#/dev/hd3  131072  9804 121268  8% /home

When I process the hash I want to sort by the percentage used in order to show the highest disk usage at the top. I know how to sort a hash by the values instead of the keys, using byval or something like this:
Code:
for (sort {$hash{$a} <=> $hash{$b}} keys %hash){

but my hash structure isn't as easy as that (I don't think).
I need to go through each filesystem, and pull out the percentage out of that hash and sort by that value.

And like I said, maybe I shouldn't even be using a hash of hashes - it seemed like a good storage method to me. This will be output on a webpage, and graphs will be created by using the data in the hash as well, so calling the hash by "used", "free", and "pused" seems like the way to go, but I will wait and see if anyone else has something to say.

Thanks in advance!

Brian
 
I tinkered with my previous method to sort it. I'm not sure if it's right or not, but this is what I did:

Code:
for (sort {$hash{$b}{"pused"} <=> $hash{$a}{"pused"}} keys %hash){

I was making it too complicated - I just had to take a step away from it for a second.

I'll still take comments if this should be done differently though.

Thanks!

Brian
 
Code:
for (sort {$hash{$b}{used} <=> $hash{$b}{used}} keys %hash)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top