ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы.



5.5. 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 Recipe 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 Recipe 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, each separated by whatever $" happens to hold. You can't put newlines between pairs or "=>" within them, as we could with the other methods.

See Also

The $" variable in perlvar (1) and in the "Global Special Variables" section of Chapter 2 of Programming Perl; the foreach, map, keys, sort, and each functions in perlfunc (1) and Chapter 3 of Programming Perl; we give a technique for interpolating into strings in Recipe 1.10; we discuss the techniques for hash traversal in Recipe 5.4


Previous: 5.4. Traversing a HashPerl CookbookNext: 5.6. Retrieving from a Hash in Insertion Order
5.4. Traversing a HashBook Index5.6. Retrieving from a Hash in Insertion Order