satzbu has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks i want to print hash keys and values without changing the order what can i do for that for example

#!/usr/bin/perl #hash2.plx use warnings; use strict; my %where=( Gary => "Dallas", Lucy => "Exeter", Ian => "Reading", Samantha => "Oregon" ); for (keys %where) { print "$_ lives in $where{$_}\n"; } _OUTPUT_ Samantha lives in Oregon Gary lives in Dallas Lucy lives in Exeter Ian lives in Reading _EXPECTED OUTPUT_ Gary lives in Dallas Lucy lives in Exeter Ian lives in Reading Samantha lives in Oregon

that means i want to print the keys and values without changing the order

Replies are listed 'Best First'.
Re: Hash error
by toolic (Bishop) on Apr 20, 2010 at 17:57 UTC
Re: Hash error
by ikegami (Patriarch) on Apr 20, 2010 at 17:55 UTC
    use warnings; use strict; my @where = ( [ Gary => "Dallas" ], [ Lucy => "Exeter" ], [ Ian => "Reading" ], [ Samantha => "Oregon" ], ); for (@where) { print "$_->[0] lives in $_->[1]\n"; }
Re: Hash error
by almut (Canon) on Apr 20, 2010 at 17:54 UTC
Re: Hash error
by AR (Friar) on Apr 20, 2010 at 18:03 UTC

    The above monks gave you solutions to what you asked for. I'm going to speak briefly on why it doesn't work the way you are expecting.

    Hashes in Perl are not meant to maintain the order in which they are built. We already have arrays for that specific reason. When you access the keys of the hash, they are returned in an order which is related to the hashing function applied to the key. When you choose to use a hash, it's assumed you are not going to want to access the entries by any means other than the keys. If you want to do so, you'll need something more complicated, like what the above monks suggest.

Re: Hash error
by Old_Gray_Bear (Bishop) on Apr 20, 2010 at 20:19 UTC
    You do realize that a Hash Table has its own idea of the order of the keys?

    If key order is really important to you, then you need to either use a module that keeps track of the order under the covers; sort the keys into the 'proper order' and then retrieve the values based on the sorted-key; or accept the fact that Hash order is in neither time-sequence nor alphabetical-order.

    ----
    I Go Back to Sleep, Now.

    OGB