Tweet

How do I print a hash that has a hash within it?

You have a hash, within which one element is a reference to another hash:

    my %hash = (
        a => {
            1 => "one",
            2 => "two",
            3 => "three",
        },
        b => {
            4 => "four",
            5 => "five",
            6 => "six",
        },
    );

Solution 1

There are two simple ways to approach this. Firstly you could use embedded 'for' loops:

    #!/usr/bin/perl -w
    use strict;

    my %hash = (
        a => {
            1 => "one",
            2 => "two",
            3 => "three",
        },
        b => {
            4 => "four",
            5 => "five",
            6 => "six",
        },
    );

    foreach my $line (keys %hash) {
        print "$line: \n";
        foreach my $elem (keys %{$hash{$line}}) {
            print "  $elem: " . $hash{$line}->{$elem} . "\n";
        }
    }

    exit 0;

This produces the following output:

    a:
      1: one
      2: two
      3: three
    b:
      4: four
      5: five
      6: six

Solution 2

A simple solution, if you only need to output the data, is to use a module called Data::Dumper. This module will handle very complex data structures, and will even nicely handle recursive references (an element in the hash points to a hash, in which an element points back to the first hash). Data::Dumper handles hashes, arrays, and combinations of both.

    #!/usr/bin/perl -w
    use strict;
    use Data::Dumper;

    my %hash = (
        a => {
            1 => "one",
            2 => "two",
            3 => "three",
        },
        b => {
            4 => "four",
            5 => "five",
            6 => "six",
        },
    );

    print Dumper(\%hash);
    exit 0;

This produces the following output:

    $VAR1 = {
              'a' => {
                       '1' => 'one',
                       '2' => 'two',
                       '3' => 'three'
                     },
              'b' => {
                       '4' => 'four',
                       '5' => 'five',
                       '6' => 'six'
                     }
            };

As you can see, the output of Data::Dumper looks like real code. You can eval the output of Data::Dumper. This makes a nice way of transfering complex data across programs that can't be called directly (e.g. through a socket, stored in a database or stored in a file).

See also

    perldoc Data::Dumper
    perldoc perldsc
Revision: 1.5 [Top]