views:

71

answers:

3

Hi,

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.

A: 

Do you mean hash of hashes? You need to tie to Tie::IxHash every value of outer hash.

use strict;
use warnings;
use Tie::IxHash;
my $hash={};
my $t = tie(%$hash, 'Tie::IxHash', 'a' => 1, 'b' => 2);
%$hash = (first => 1, second => 2, third => 3);
$hash->{fourth} = 4;
print join(', ',keys %$hash),"\n";
my %new_hash=('test'=>$hash);
$new_hash{'test'}{fifth} = 5;
print join(', ',keys %{$new_hash{'test'}}),"\n";
$new_hash{'test'}{fifth}++;
print join(', ',values %{$new_hash{'test'}}),"\n";
Alexandr Ciornii
But you only have one call to `tie` in your example.
cjm
A: 
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.

YoDar
+1  A: 

Look at Tie::Autotie. It automatically ties new hashes created by autovivification. The perldoc page shows an example using Tie::IxHash.

Philip Potter