in reply to Re: Maintainance of element order in hash
in thread Maintainance of element order in hash

In seen  Tie::IxHash but in this I am seeing only key pair value. But I dont understand how to give nested hashes into it. Can you write a small snipplet for the above example using Tie::Ixhash

Replies are listed 'Best First'.
Re^3: Maintainance of element order in hash
by hippo (Archbishop) on Sep 29, 2016 at 13:43 UTC
    I dont understand how to give nested hashes into it
    #!/usr/bin/env perl # Hash order maintained use strict; use warnings; use Test::More tests => 1; use Tie::IxHash; tie my %foo, 'Tie::IxHash'; $foo{a} = [3, 2, 1]; $foo{b} = { s => 'senatus', p => 'populus', q => 'que', r => 'romanus' + }; is_deeply ([keys %foo], [qw/a b/], 'Order retained');

    and see perldsc for how to use nested data structures generally.

      Thanks for reply. I tried this by using your example. But when I dumping the hash it is not in the ordered as we inserted. Where I am missing the logic???

      #!/usr/bin/env perl # Hash order maintained use strict; use warnings; use Test::More tests => 1; use Tie::IxHash; use Data::Dumper; tie my %foo, 'Tie::IxHash'; $foo{a}{c} = [3, 2, 1]; $foo{a}{b}{x} = { s => 'senatus', p => 'populus', q => 'que', r => 'ro +manus'}; $foo{a}{b}{y} = "ravi"; print Dumper \%foo;

        There is no point whatsoever in tieing a hash like %foo to retain the order of its keys when it only has one key as in your example, which is "a". Likewise any subhashes which are untied will not retain the order of their keys. If you wish to retain the order all the way down for some reason then you need to tie all your hashes.

        #!/usr/bin/env perl # Subhash order maintained use strict; use warnings; use Test::More tests => 3; use Tie::IxHash; tie my %a, 'Tie::IxHash'; tie my %b, 'Tie::IxHash'; tie my %x, 'Tie::IxHash'; my %foo; $a{c} = [3, 2, 1]; %x = ( s => 'senatus', p => 'populus', q => 'que', r => 'romanus'); %b = ( x => \%x, y => "ravi" ); $a{b} = \%b; $foo{a} = \%a; is_deeply ([keys %{$foo{a}}], [qw/c b/], '1st level order re +tained'); is_deeply ([keys %{$foo{a}{b}}], [qw/x y/], '2nd level order re +tained'); is_deeply ([keys %{$foo{a}{b}{x}}], [qw/s p q r/], '3rd level order re +tained');

        This all still very much sounds like an XY Problem, however.