Search code examples
arraysperlhashperl-data-structures

Perl: dereferencing an hash of hash of hashes


consider the sample code:

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

                                }
            }
    };

i return it as reference, return \%hash

how do i dereference this?


Solution

  • %$hash. See http://perldoc.perl.org/perlreftut.html for more information.

    If your hash is returned by a function call, you can do either:

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

    Or:

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

    To access values within your hash, you can use the -> operator.

    $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