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

RE: sort order of hash keys

Thread Previous | Thread Next
John Edwards
February 26, 2002 02:33
RE: sort order of hash keys
Message ID:
hash keys are stored unsorted. If you have the following hash

%test = (	one => 1,
		two => 2,
		three => 3);

and print out the hash key/value pairs.

foreach $key (keys %test) {
	print "$key is $test{$key}\n";

you will find they don't come out in the same order as they were stored.

You can perform a sort on the keys to arrange them in order

foreach $key (sort keys %test) {
	print "$key is $test{$key}\n";

or you can reverse the hash, making the values the keys, and sort on the new

%reversed = reverse %test;

foreach $key (keys %reversed) {
	print "$key is $reversed{$key}\n";

In doing this though, you must be aware that you will lose any data that has
identical values. For example

%test = (	one => 1,
		two => 2,
		three => 3,
		alpha => 1,
		beta => 2,
		gamma => 3);

%reversed = reverse %test;

foreach $key (keys %reversed) {
	print "$key is $reversed{$key}\n";

will print out

1 is one
2 is two
3 is three

There is probably another/better way of doing this using the comparison
operator <=>, but I don't know it. There is also a module available that
lets you store and retrieve hashes in a fixed order.
-----Original Message-----
From: []
Sent: 26 February 2002 09:16
Subject: sort order of hash keys


i would like to know if theres a smart way to unwind a hashtable so that
the key / value pairs comes out in the same order as they are in the table.



To unsubscribe, e-mail:
For additional commands, e-mail:

This E-mail is confidential.  It should not be read, copied, disclosed or
used by any person other than the intended recipient.  Unauthorised use,
disclosure or copying by whatever medium is strictly prohibited and may be
unlawful.  If you have received this E-mail in error please contact the
sender immediately and delete the E-mail from your system.

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About