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

Re: sort order of hash keys

Thread Previous | Thread Next
From:
maasha
Date:
February 26, 2002 03:37
Subject:
Re: sort order of hash keys
Message ID:
20020226113703.GK1066@image
yeah, i new this was tricky.

my hash keys / values have uneven names so i cant use a sort routine directly. thats why i would like to get the key / values in the same order as they are in the hashtable file.

whats the name of that hash modules?

:o)

martin


On Tue, Feb 26, 2002 at 10:28:16AM -0000, John Edwards wrote:
> 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
> keys
> 
> %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: maasha@image.dk [mailto:maasha@image.dk]
> Sent: 26 February 2002 09:16
> To: beginners@perl.org
> Subject: sort order of hash keys
> 
> 
> hi
> 
> 
> 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.
> 
> :o)
> 
> martin
> -- 
> 
> -- 
> To unsubscribe, e-mail: beginners-unsubscribe@perl.org
> For additional commands, e-mail: beginners-help@perl.org
> 
> 
> --------------------------Confidentiality--------------------------.
> 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


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