2017-03-29 4 views
0

J'ai donc un hachage massif de hachages.Imprimer le nom de hachage d'un hachage de hachages de hachages etc

$VAR1 = { 
      'Peti Bar' => { 
          'Mathematics' => 82, 
          'Art' => 99, 
          'Literature' => 88 
         }, 
      'Foo Bar' => { 
         'Mathematics' => 97, 
         'Literature' => 67 
         } 
     }; 

Voici un exemple que j'ai trouvé sur le Web. Ce que je veux imprimer est 'Peti Bar' et 'Foo Bar', mais ce n'est pas aussi simple que ça. Imaginez les mathématiques étant son propre hachage dans ce hachage, etc. Donc je voudrais imprimer 'Peti Bar' -> 'Mathématiques' -> 'AnotherHash' 'Foo Bar' -> 'Literature' -> 'Anotherhash'

Je suppose que peut-être ce que je demande est d'imprimer le hachage des hachages sans clé/valeur de chaque hachage respectif.

+0

'' >><< '' http://perldoc.perl.org/perldsc.html#Access-and-Printing-of-a-HASH-OF-HASHES –

Répondre

1

La façon la plus simple est probablement d'utiliser une fonction récursive pour passer par le hachage de niveau supérieur et des subhashes, l'impression des clés qui ont subhashes avant de descendre dans le Subhash:

#!/usr/bin/env perl  

use strict; 
use warnings; 
use 5.010; 

my %bighash = (
    'Peti Bar' => { 
    'Mathematics' => {  
     'Arithmetic' => 7,  
     'Geometry' => 8,  
     'Calculus' => 9,  
    }, 
    'Art'  => 99, 
    'Literature' => 88  
    },      
    'Foo Bar' => { 
    'Mathematics' => 97, 
    'Literature' => 67 
    }      
);  

dump_hash(\%bighash); 

sub dump_hash { 
    my $hashref = shift; 
    my @parents = @_; 

    return unless $hashref && ref $hashref eq 'HASH'; 

    for my $key (sort keys %$hashref) { 
    my $val = $hashref->{$key}; 
    next unless ref $val eq 'HASH'; 
    say join ' -> ', @parents, $key; 
    dump_hash($val, @parents, $key); 
    } 
} 

Sortie:

Foo Bar 
Peti Bar 
Peti Bar -> Mathematics 
0

similaires à Dave S

use strict; 

my $VAR1 = { 
      'Peti Bar' => { 
          'Mathematics' => 82, 
          'Art' => 99, 
          'Literature' => 88 
         }, 
      'Foo Bar' => { 
         'Mathematics' => 97, 
         'Literature' => 67 
         } 
     }; 


sub printHash($$) { 
    my $hashRef = shift; 
    my $indent = shift; 
    for (keys %$hashRef) { 
     if (ref($hashRef->{$_}) eq 'HASH') { 
      print "$indent$_ \n"; 
      printHash($hashRef->{$_},"\t$indent"); 
     } 
     else { 
      print "$indent$_ $hashRef->{$_}\n"; 
     } 
    } 
} 

printHash($VAR1,undef); 

sortie est:

Foo Bar 
     Mathematics 97 
     Literature 67 
Peti Bar 
     Literature 88 
     Mathematics 82 
     Art 99