Printing a Hash

Problem

You want to print a hash, but neither print "%hash" nor print %hash works.

Solution

One of several approaches is to iterate over every key-value pair in the hash using Section 5.4, and print them:

while ( ($k,$v) = each %hash ) {
    print "$k => $v\n";
}

Or use map to generate a list of strings:

print map { "$_ => $hash{$_}\n" } keys %hash;

Or use the interpolation trick from Section 1.10 to interpolate the hash as a list:

print "@{[ %hash ]}\n";

Or use a temporary array variable to hold the hash, and print that:

{
    my @temp = %hash;
    print "@temp";
}

Discussion

The methods differ in the degree that their output is customizable in order and formatting and in their efficiency.

The first method, iterating over the hash, is very flexible and space-efficient. You can format the output as you like it, and it only requires two scalar variables: the current key and value. You can print the hash in key order (at the cost of building a list of sorted keys) if you use a foreach loop.

foreach $k (sort keys %hash) {
    print "$k => $hash{$k}\n";
}

The map function is just as flexible. You can still process the list in any order by sorting the keys. You can customize the output to your heart’s content. But it builds up a list of strings like "KEY =>VALUE\n" to pass to print.

The last two methods are interpolation tricks. By treating the hash as an list, you can’t predict or control the output order of the key-value pairs. Furthermore, the output will consist of a list of keys and values, ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.