http://www.perlmonks.org?node_id=968093

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


Hi Monk,
I have used Tie::IxHash module to retrieve the hash key values in the order of their insertion. Is their any other way to get the key-values in the same order they appear in the hash without using Tie::IxHash module ?
Thanks.

Replies are listed 'Best First'.
Re: Retrieving the hash key-value in the order of their insertion without Tie::IxHash
by ikegami (Patriarch) on Apr 30, 2012 at 15:37 UTC
    Hashes do not record track insertion order, so you have to use a different data structure to do so. Tie::IxHash allows you to keep the same interface as a hash without actually being (just) a hash, but that's not necessary if you want something less magical.
Re: Retrieving the hash key-value in the order of their insertion without Tie::IxHash
by Corion (Patriarch) on Apr 30, 2012 at 15:19 UTC

      I do not want to avoid Tie::IxHash. I just want to know if there is any other way of achieving this. I am curious.

Re: Retrieving the hash key-value in the order of their insertion without Tie::IxHash
by johngg (Canon) on Apr 30, 2012 at 17:38 UTC

    One way is to use a HoH and keep the insertion order alongside the data.

    knoppix@Microknoppix:~$ perl -Mstrict -wE ' > my @keys = qw{ pete bill mary jack dave leah }; > my $order = 0; > my %hash; > > foreach my $key ( @keys ) > { > $hash{ $key } = { data => $order * 2, order => ++ $order }; > } > > say qq{$_ => $hash{ $_ }->{ data } } > for sort { $hash{ $a }->{ order } <=> $hash{ $b }->{ order } } > keys %hash;' pete => 0 bill => 2 mary => 4 jack => 6 dave => 8 leah => 10 knoppix@Microknoppix:~$

    I hope this is helpful.

    Cheers,

    JohnGG

      That's fine for a bulk insert, but if he wanted to keep manipulating the hash it gets pretty cumbersome to upkeep.

      Strange things are afoot at the Circle-K.
Re: Retrieving the hash key-value in the order of their insertion without Tie::IxHash
by JavaFan (Canon) on Apr 30, 2012 at 15:58 UTC
    Some ways:
    1. Use a tied hash, and do something similar to Tie::IxHash;
    2. Use an additional data structure, and consult this one when retrieving keys. Don't forget to update this datastructure each time you modify your hash.
    3. Don't use hashes with more than one key.