l_millr has asked for the wisdom of the Perl Monks concerning the following question:

I'm sure there's an answer to this question, but I don't know the right term to use to find it. If I search for hash I get a lot of info about hashes but nothing about this:
#!/usr/local/bin/perl %c={A=>'0',B=>'0',C=>'0',D=>'0'}; foreach $key (keys %c) { print "$key => $c{$key}\n"; }
Output is:
HASH(0x1b9550c) =>

Why? Shouldn't this code print all the values of %c?

=================================

You know what? I answered my own question, so now it's an FYI for idjits like me.

The problem here is (1) I'm stupid and (2) I need to learn the difference between {} which creates an anonymous hash and () which specifies a list of values.

So %c={A=>'0',B=>'0',C=>'0',D=>'0'}; gives HASH() because you've told perl to add a self-contained hash as the key for the first value of %c.

Extra credit: What is the value of that first key? Nothing, because all you've specified is the key.

BUT %c=(A=>'0',B=>'0',C=>'0',D=>'0'); gives A=>0, B=>0, C=>0, D=>0 because you've told perl to add four key/value pairs to %c.

I hope this helps someone, because this forum has been extremely helpful to me. If some newbie can avoid getting a divorce because he doesn't have to spend 4 hours at work figuring this out like I did, I will be a happy person.

Replies are listed 'Best First'.
Re: Trying to print the contents of a hash, but getting a reference.
by IlyaM (Parson) on Dec 17, 2001 at 02:17 UTC
    Were you used warnings it could be much more easier for you to find reason for your problem.

    With warnings turned on your program yeilds warning:

    Reference found where even-sized list expected at ...
    for line
    c={A=>'0',B=>'0',C=>'0',D=>'0'};
    And with use diagnostics you could get even more detailed explanation of problem:
    Reference found where even-sized list expected (W misc) You gave a single reference where Perl was expecting a list with an even number of elements (for assignment to a hash). This usually means that you used the anon hash constructor when you meant to use parens. In any case, a hash requires key/value pairs. %hash = { one => 1, two => 2, }; # WRONG %hash = [ qw/ an anon array / ]; # WRONG %hash = ( one => 1, two => 2, ); # right %hash = qw( one 1 two 2 ); # also fine
    So conclusion is: use strict warnings and diagnostics or die.