![]() |
![]() |
![]() |
||||
Welcome to the GoFuckYourself.com - Adult Webmaster Forum forums. You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, join our community today! If you have any problems with the registration process or your account login, please contact us. |
![]() ![]() |
|
Discuss what's fucking going on, and which programs are best and worst. One-time "program" announcements from "established" webmasters are allowed. |
|
Thread Tools |
![]() |
#1 |
Confirmed User
Industry Role:
Join Date: Jul 2003
Posts: 5,344
|
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" ); |
![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
#2 |
Confirmed User
Join Date: May 2001
Location: ICQ: 25285313
Posts: 993
|
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..
__________________
Quality affordable hosting. |
![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
#3 |
So Fucking Banned
Join Date: Jan 2005
Location: At My Desk
Posts: 2,904
|
foreach $code (sort { $countries{$a} cmp $countries{$b} } keys %countries) { do this...
|
![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
#4 |
Pounding Googlebot
Industry Role:
Join Date: Aug 2002
Location: Canada
Posts: 34,482
|
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
__________________
I play with Google. |
![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
#5 | |
Registered User
Industry Role:
Join Date: Mar 2002
Location: San Diego, CA
Posts: 935
|
Quote:
foreach $Key ( sort %hash ) { print "$Key => " . $hash{$Key} . "\n"; } |
|
![]() |
![]() ![]() ![]() ![]() ![]() |