List Info

Thread: Sort hash by keys




Sort hash by keys
country flaguser name
United States
2007-09-19 09:05:16

I have a hash. I want to sort it by its keys and maintain its newly
sorted version. I know you can use sort keys but isn't there a simple one
liner to take a hash, sort it by its keys, and retain the sort from
there-on?

------------------------
Ryan Nauman
Business Intelligence
Decision Support
(412) 433-1737

[Non-text portions of this message have been removed]

__._,_.___
.

__,_._,___
Re: Sort hash by keys
country flaguser name
United States
2007-09-19 09:27:25

On 9/19/07, Ryan J Nauman < RJNauman%40uss.com">RJNaumanuss.com&gt; wrote:
&gt; I have a hash. I want to sort it by its keys and maintain its newly
&gt; sorted version. I know you can use sort keys but isn't there a simple one
> liner to take a hash, sort it by its keys, and retain the sort from
>; there-on?

No. Hashes maintain an internal order that can change over time as
more keys are added (or deleted). If you want to keep the keys of a
hash in a particular order, store them in an array:

my keys_in_order = sort keys %hash;

Then you can use keys_in_order to walk through your hash in a
particular order. There are also modules you can use to intervene,
which would make what appears to be a regular hash actually one that
always keeps its keeps sorted. The Tie::Hash::Sorted module does just
that:

use Tie::Hash::Sorted;
tie my %sorted_hash, 'Tie::Hash::Sorted';

Then just use %sorted_hash like it's a regular hash, and you'll find
that every time you access its keys, you'll get them in sorted order.

--
So he got up and went back to his father. While he was still a long
way off, his father caught sight of him, and was filled with
compassion. He ran to his son, embraced him and kissed him. ~ Luke
15:20

[Mary said,] "Do whatever he tells you." ~ John 2:5

__._,_.___
.

__,_._,___
[1-2]

about | contact  Other archives ( Real Estate discussion Medical topics )