打印散列哈希哈希值的哈希名称

时间:2017-03-29 06:45:37

标签: perl hash hash-of-hashes

所以我有一大堆哈希。

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

我在网上找到了一个例子。

我想要打印的是'Peti Bar'和'Foo Bar',但它并不那么简单。想象一下数学就是它在哈希等中的自己的哈希所以我想要打印'Peti Bar' - > '数学' - > 'AnotherHash' 'Foo Bar' - > '文学' - > 'Anotherhash'

我想也许我要问的是打印散列的散列而没有每个散列的键/值。

2 个答案:

答案 0 :(得分:1)

最简单的方法可能是使用递归函数来遍历顶级哈希和任何子哈希,在下降到子哈希之前打印任何具有子哈希的键:

#!/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);
  }
}

输出:

Foo Bar
Peti Bar
Peti Bar -> Mathematics

答案 1 :(得分:0)

与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);

输出是:

Foo Bar
        Mathematics  97
        Literature  67
Peti Bar
        Literature  88
        Mathematics  82
        Art  99
相关问题