5.5. Printing a HashProblem
You want to print a hash, but neither SolutionOne 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 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"; } DiscussionThe 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 $k (sort keys %hash) { print "$k => $hash{$k}\n"; }
The
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 See Also
The Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|