Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with sorting

Status
Not open for further replies.

KeziaKristina

Programmer
Nov 1, 2002
13
ID
I have source code something like this :
%HoA = (
'$b' => ['$x','$y'],
'$x' => ['$t','$u'],
'$a' => ['$e','$f','$g'],
);

#sort hash by the number of elemens
for $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA )
{
print &quot;$family: @{ $HoA{$family} }\n&quot;;
}
print &quot;After sorting : &quot;;
for $family (keys %HoA ) {
print &quot;$family: @{ $HoA{$family} }\n&quot;
}
my question is :
Why after sorting process, the elemen of hash still the same like before sorting?
 
Hi!, when you use sort function you have to assign the return value to a variable, the parameter don't change.

I don't know if a hash can be sort.
 
That code would be work if the hash like this:
%HoA = (
animal => [&quot;tiger&quot;],
fruit => [&quot;banana&quot;,&quot;starfruit&quot;,&quot;melon&quot;],
country => [&quot;Australia&quot;,&quot;England&quot;]
);
And after sorting the hash would be :
%HoA = (
fruit => [&quot;banana&quot;,&quot;starfruit&quot;,&quot;melon&quot;],
country => [&quot;Australia&quot;,&quot;England&quot;],
animal => [&quot;tiger&quot;]
);
I confuse, cos that is not work with my hash. I get the code from the Programming Perl book, for sorting hash by the number of its elements.
Anybody can help me?

~Kristina~
 
A hash is by definition an associative array. You retrieve data not by their positions, but by their keys. Hash keys have no order, perl stores them internally in whatever way it sees it can work with it most efficiently. You could make an array to work around it.
Code:
%HoA = (
	animal => [&quot;tiger&quot;],
	fruit => [&quot;banana&quot;,&quot;starfruit&quot;,&quot;melon&quot;],
	country => [&quot;Australia&quot;,&quot;England&quot;]
);

@HoAKeys = sort {$b cmp $a} keys %HoA;

foreach $family (@HoAKeys)
{
	print &quot;$family: @{$HoA{$family}}\n&quot;;
}
This sorts the hash keys in descending order, but stores them in an array. Then you loop over the array, but still use each element as a hash key, and you should get your reverse ordering.

If you're only looping once, you already had it above where the array to loop over is the sorted hash keys, but if you want to do it again later without resorting, you'd have to store that order.

If you ever update the hash with more or fewer values, you would have to update the ordered array of keys, too, before using it. ----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top