Page 64      All Pages  All Books
{  # HASH(0xb78b00)
:    3 => 4
:    hello =>
:    : [ # ARRAY(0xc70858)
:    : : 6
:    : : 7
:    : ]
}
The following code contains specialized procedures (print_array, print_hash, or print_scalar) that know how to print specific data types. print_ref, charged with the task of pretty-printing a reference, simply dispatches control to one of the above procedures depending upon the type of argument given to it. In turn, these procedures may call print_ref recursively if the data types that they handle contain one or more references.
Whenever a reference is encountered, it is also checked with a hash %already_seen to determine whether the reference has been printed before. This prevents the routine from going into an infinite loop in the presence of circular references. All functions manipulate the global variable $level and call print_indented, which appropriately indents and prints the string given to it.
Example 2.5: Pretty-Printing
$level = -1; # Level of indentation
sub pretty_print { my $var; foreach $var (@_) {
if (ref ($var)) {
print_ref($var); } else {
print_scalar($var); } } }
sub print_scalar {
++$level;
my $var = shift;
print_indented ($var);
--$level; }
sub print_ref {
my $r = shift;
if (exists ($already_seen{$r})) {
print_indented ("$r (Seen earlier)");

Page 64      All Pages  All Books