[Perl] printing a hash

Reuven M. Lerner reuven at lerner.co.il
Mon Jun 24 05:58:11 PDT 2002


>>>>> "Offer" == Offer Kaye <oferk at oren.co.il> writes:

    Offer> print "%arr_hash1\n"; 
    Offer> print %arr_hash1, "\n";

    Offer> i.e. the second "print" worked as I expected, the first did
    Offer> not. How come?

In the first case, the hash was inside of double quotes.  Scalars and
arrays are interpolated into double quotes, but hashes aren't.  So
Perl prints the hash name as you entered it.

In the second case, you put the hash outside of double quotes.  This
is one of those cases when the boundary between hashes and lists is a
bit thin: Perl turns the hash into a list (since perl handles its
arguments in list context), and then prints the arguments.    The
hash is turned into a list, sort of like the list you use to
initialize a hash:

    my %arr_hash1 = ('1' , 'do' , '2' , 're' , '3' , 'me' ,
		     '4' , 'fa' , '5' , 'so' , '6' , 'la' ,
		     '7' , 'se' , '8' , 'do');

Or somewhat more readably:

    my %arr_hash1 = ('1' => 'do' , '2' => 're' , '3' => 'me' ,
		     '4' => 'fa' , '5' => 'so' , '6' => 'la' ,
		     '7' => 'se' , '8' => 'do');

print doesn't put any whitespace or other separators between items it
prints, so you get all of the keys and values from your hash mushed
together.  In other words, you basically did the same thing as this:

    print 1, 2, 3, "\n";

Which of course produces the output:

    123

Remember that you can't reasonably expect to know the order of pairs
in a hash.  But you *can* be sure that keys will be at even indexes
(0, 2, 4, etc.) and values will be at odd indexes (1, 3, 5, etc.), and
that key-value pairs will be together.

If you really want to display a hash for debugging purposes, there are
lots of ways to do it. I generally do something like:

    foreach my $Key (sort keys %hash)
    {
	print "'$key' => '$hash{$key}'\n";
    }

I always put a delimiter around the key and value (single quotes, in
this case0 so that I don't get confused if the variable is empty,
contains whitespace, or is otherwise hard to understand.

Reuven



More information about the Perl mailing list