2010-08-04 123 views
2

如何保存散列元素的添加顺序 对于第二个VAR?Tie :: IxHash在哈希哈希中排序关联数组?

(哈希值的哈希值)

例如:

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); 

当倾倒出来的结果,$ VAR14没有保留插入顺序:

$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 
     }; 

我知道我可以用一些排序操作来欺骗这个例子,但在我真正的问题中,这些元素没有编号,或者无法排序。 是否有任何简单的函数/操作散列多级顺序插入?

谢谢,

Yodar。

+1

这看起来像Dumper输出。如果是这种情况,那么'$ VAR1'就是*字符串*'FIRSTVAL'。请显示可以转储的代码。这看起来不像IxHash内部。 – Axeman 2010-08-04 15:14:39

回答

-1
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有用的答案帮助了我。

0

你是指散列哈希?你需要绑定到Tie :: IxHash每个外部哈希值。

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"; 
+2

但是在你的例子中你只有一个叫'tie'的电话。 – cjm 2010-08-04 16:45:27

5

看看Tie::Autotie。它会自动绑定由自动版本创建的新哈希。 perldoc页面显示了一个使用Tie :: IxHash的例子。

2

您需要额外的“\”,如下所示。

print Dumper(\%hash);