2013-05-15 130 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