|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
When I get the keys of a hash, the keys are returned in some random order.
How can I prevent this without changing key names (to sort them alfabetically afterwards)? Thanks in advance, d0g1e |
|
#2
|
|||
|
|||
|
hashes by their very nature keep track of their contents in a random order ..
there is no way to know which order they will return values in. |
|
#3
|
||||
|
||||
|
You could take each key from the hash, "push" it into an array, the do a sort on the array to view each key alphabetically. Possibly one appoarch.
Mickalo
__________________
Thunder Rain Internet Publishing Custom Programming & Database development Providing Personal/Business Internet Solutions that work! |
|
#4
|
|||
|
|||
|
or do it all in one line of code
Code:
@array = sort { lc($hash{$a}) cmp lc($hash{$b}) } keys %hash;
|
|
#5
|
|||
|
|||
|
You just need to use sort{} in your loop:
Code:
foreach $key (sort {$a cmp $b} keys %hash) {
print $key, ': ', $hash{key}, $/;
}
|
|
#6
|
|||
|
|||
|
Also now that sort {$a cmp $b} will sort by the key. sort {$hash{$a} cmp $hash{$b}} will sort by the value (i think someone above misstated this)
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Perl Programming > getting keys in a hash without changing the order |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|