![]() |
how to (really) sort a hash by key in Perl
lets I have a hash:
%hash=( '2004' => "red", '2006' => "blue", '2005' => "green" ); how do I sort it by key? i don't want to print it out sorted, only sort it using this: @keys = sort keys %hash; will NOT work, because @keys now contain only the keys why is it so fucking hard to get this: %hash=( '2004' => "red", '2005' => "green", '2006' => "blue" ); |
You cannot "keep" a hash sorted, it's simply not how hashes work.
Do what you did w/ array storing the keys. Then foreach that array when you want to perform an ordered operation on the hash. Depending on the application of course there are better ways, but considering what posts you've made on the subject this should be fine. Arrays will keep their order of course. Just do something like.. foreach my $key (@keys) { my $value=$hash{$key}; print "key $key - value $value\n"; ... } Shrug.. |
foreach $code (sort { $countries{$a} cmp $countries{$b} } keys %countries) { do this...
|
You can't actually sort the hash but as teksonline said you can have the ordering permutted with that code and do whatever you want at runtime. The actual data can't be sorted like an array though.
WG |
Quote:
foreach $Key ( sort %hash ) { print "$Key => " . $hash{$Key} . "\n"; } |
All times are GMT -7. The time now is 03:27 PM. |
Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
©2000-, AI Media Network Inc123