Perl:解引用哈希的哈希的哈希

4

考虑以下示例代码:

$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',

                                }
            }
    };

我将其作为引用返回,返回\%hash。

我该如何取消引用?

2个回答

8

%$哈希。有关更多信息,请参见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

我想完全取消引用它。尝试了你说的方法,但不起作用。它只取消引用第一个哈希。 - dreamer
你能给我一个你正在尝试做的代码示例吗?顺便说一下,我参考的教程非常有帮助。 - 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};
其中,$VAR1 是一个包含键值对的变量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接