develooper Front page | perl.beginners | Postings from January 2002

Printing Ordered Hash Values

Thread Next
From:
RArul
Date:
January 31, 2002 07:52
Subject:
Printing Ordered Hash Values
Message ID:
78B385FB8F70D511857900B0D0D06A587082F6@mail.newenergyassoc.com
I have a simple hash with directory names as keys and sizes as values. I
would like to print the hash, in descending order of the size of each
directory.

I was contemplating of "reversing" the hash(so that sizes become keys and
directory names become values) and then do a sort on the keys. However, this
approach would not work if two directories have the same sizes, as that
would "flatten" the keys list!

In my code snippet below, C:/rex and C:/mail have same sizes and therefore
the end-result would have just one of the two. Therefore, is there a
straight-forward way that I am missing? Of course, I can do some extra
array-processing to report the results. I am just curious to find if there
is a straight-forward way.

Thanks,
Rex

###############################
#!/usr/bin/perl
use strict;
use warnings;
my(%hash);
$hash{'c:/rex'}	= 100;
$hash{'c:/perl'}	= 50;
$hash{'c:/temp'}	= 75;
$hash{'c:/mail'}	= 100;
print("\n\nBefore Reversing.... \n");
map{ print("$_ ===> $hash{$_}\n") } keys %hash;
%hash	=	reverse(%hash);
print("\n\nAfter Reversing and Sorting...\n");
map{ print("$hash{$_} ===> $_ \n") } sort{$b <=> $a} keys %hash;
###############################

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About