Perl: dereferencing a hash hash a hash

consider a code example:

$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 a link, return \% hash

How do I play this?

+4
source share
2 answers

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

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 the values ​​in 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 
+7
source

try something like below might be useful for you:

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

Also, if you want to access a specific key, you can do it like

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

+3
source

Source: https://habr.com/ru/post/1480862/


All Articles