Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hello all,

While printing a hash , I am not getting the values in order , in which I defined in a hash.
Example:
my $hash=(
         'bangalore'=>'20',
         'Mumbai'=>'23',
         'pune'=>'45',
         'aligarh'=>'56'
         );

so if I print this hash, there is no guarantee that it will print in the same order as i defined :mad:, I mean while printing the hash mumnai may come first and then bangalore , so can someone help me in understanding why am I not getting the values in order as I defined in hash.

* above hash is just an example
my actulay hash contains some command which I need to run one by one (order is very important while executing the command).
I know, I can use array in this case :)
BUT can some one explain how hash stores data in memory , and if I want to print the values in order as I defined in hash , how to do that?

:confused:
Posted
Updated 16-Feb-11 18:30pm
v3

1 solution

Hashes in perl are called hashes because they store the data in a hash table. Hash tables use a hash function to calculate a key based on the value you give it and allow for fast searches at the expense of memory.

Using your example, say the hash table has 26 entries, and the hash function uses the first letter (case insensitive) to determine where to put each item in the table. So the hash table would look something like:

 0: 'aligarh'=>'56'
 1: 'bangalore'=>'20'
 2:
 3:
...
12: 'Mumbai'=>'23'
...
15: 'pune'=>'45'
...
25:


The insertion order will not affect the order in the hash table, otherwise there would be no way to look up a value later without knowing when it was inserted. Thus, no matter what order you insert items into the hash, the hash table will end up in the same state. In real-world uses, the hash function is more complicated to reduce collisions (two keys being put in the same slot).

So, to answer your question "if I want to print the values in order as I defined in hash, how to do that?", the answer is that you can't without using something besides just the hash (either an array, or some other variable keeping track of insertion order, or maybe by reading in your perl file and parsing it if you're really looking for a fun way to do it.)

For a much longer, and likely better explanation, wikipedia[^] is always a place to start.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900