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

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:

Solution 1

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

This produces the following output:

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.

This produces the following output:

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

Scroll to Top