Search code examples
perlperl-hash

Tie::IxHash ordered associative arrays in Hash of Hashes?


How can I preserve the order in which the hash elements were added FOR THE SECOND VAR ?

( Hash of Hashes )

For example:

use Tie::IxHash;
my %hash;
tie %hash, "Tie::IxHash";
for my $num (0 .. 5){
     $hash{"FirstVal$num"}++;
}
for my $num (0 .. 5){
     $hash{"FirstValFIXED"}{"SecondVal$num"}++;
}
 print Dumper(%hash);

When dumping out the result, $VAR14 didn't preserve the insertion order:

$VAR1 = 'FirstVal0';
$VAR2 = 1;
$VAR3 = 'FirstVal1';
$VAR4 = 1;
$VAR5 = 'FirstVal2';
$VAR6 = 1;
$VAR7 = 'FirstVal3';
$VAR8 = 1;
$VAR9 = 'FirstVal4';
$VAR10 = 1;
$VAR11 = 'FirstVal5';
$VAR12 = 1;
$VAR13 = 'FirstValFIXED';
$VAR14 = {
           'SecondVal5' => 1,
           'SecondVal4' => 1,
           'SecondVal2' => 1,
           'SecondVal1' => 1,
           'SecondVal3' => 1,
           'SecondVal0' => 1
         };

I know I can trick that example with some sort operation but in my real problem the elements are not numbered or can't be ordered some how. Is there any simple function/operation for hash multi level order insertion ?

Thanks,

Yodar.


Solution

  • foreach my $sortline (sort {$a<=>$b} keys %{$hash->{"first_field"}}){
        my $name;
        # Soultion to touch a Key with keys within it:
        #--------------------------------------------- 
        foreach my $subkey (keys %{$hash->{"first_field"}->{$sortline}})
                {$name = $subkey;}
        #---------------------------------------------
    }
    

    This useful answer helped me.