GoFuckYourself.com - Adult Webmaster Forum

GoFuckYourself.com - Adult Webmaster Forum (https://gfy.com/index.php)
-   Fucking Around & Business Discussion (https://gfy.com/forumdisplay.php?f=26)
-   -   how to (really) sort a hash by key in Perl (https://gfy.com/showthread.php?t=442308)

Zester 03-10-2005 04:51 AM

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"
);

Phil21 03-10-2005 04:57 AM

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..

teksonline 03-10-2005 05:15 AM

foreach $code (sort { $countries{$a} cmp $countries{$b} } keys %countries) { do this...

WiredGuy 03-10-2005 09:08 AM

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

Big E 03-10-2005 12:01 PM

Quote:

Originally Posted by teksonline
foreach $code (sort { $countries{$a} cmp $countries{$b} } keys %countries) { do this...

FYI - That sorts by VALUE, not KEY.

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