2013-05-15 94 views
4

考虑示例代码:的Perl:提领哈希散列的散列

$VAR1 = { 
     'en' => { 
       'new' => { 
         'style' => 'defaultCaption', 
         'tts:fontStyle' => 'bold', 
         'id' => 'new' 
        }, 
       'defaultCaption' => { 
            'tts:textAlign' => 'left', 
            'tts:fontWeight' => 'normal', 
            'tts:color' => 'white', 

           } 
      }, 
     'es' => { 
       'defaultSpeaker' => { 
            'tts:textAlign' => 'left', 
            'tts:fontWeight' => 'normal', 

           }, 
       'new' => { 
         'style' => 'defaultCaption', 
         'tts:fontStyle' => 'bold', 
         'id' => 'new' 
        }, 
       'defaultCaption' => { 
            'tts:textAlign' => 'left', 
            'tts:fontWeight' => 'normal', 

           } 
      } 
    }; 

我回它作为参考, 回报\%哈希

我如何提领呢?

回答

7

%$hash。有关更多信息,请参见http://perldoc.perl.org/perlreftut.html

如果你的哈希通过函数调用返回,则可以执行:

my $hash_ref = function_call(); 
for my $key (keys %$hashref) { ... # etc: use %$hashref to dereference 

或者:

my %hash = %{ function_call() }; # dereference immediately 

要访问值的散列中,你可以使用->操作。像下面

$hash->{en}; # returns hashref { new => { ... }. defaultCaption => { ... } } 
$hash->{en}->{new};  # returns hashref { style => '...', ... } 
$hash->{en}{new};  # shorthand for above 
%{ $hash->{en}{new} }; # dereference 
$hash->{en}{new}{style}; # returns 'defaultCaption' as string 
+0

我想要完全解除引用。试过你说的话。这是行不通的。它只解引用第一个散列。 – dreamer

+0

你能给我一个你想要做什么的代码示例吗?我引用的教程很有帮助,顺便说一句。 – rjh

3

试一下,也许对您会有所帮助:

my %hash = %{ $VAR1}; 
     foreach my $level1 (keys %hash) { 
      my %hoh = %{$hash{$level1}}; 
      print"$level1\n"; 
      foreach my $level2 (keys %hoh) { 
       my %hohoh = %{$hoh{$level2}}; 
       print"$level2\n"; 
       foreach my $level3 (keys %hohoh) { 
         print"$level3, $hohoh{$level3}\n"; 
       } 
      } 
     } 

此外,如果您要访问的特定键,你可以不喜欢它

my $test = $VAR1->{es}->{new}->{id};

+0

天才!谢谢! – jouell