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

I have this code which is not working.
#!/usr/bin/perl use strict; use Data::Dumper; my $test = { record => '' }; $test->{record}->{'a'} = 11; $test->{record}->{'b'} = 22; print Dumper \$test;
I am hoping to get this output.
$VAR1 = \{ 'record' => { 'a' => 11, 'b' => 22 } };

I am getting this error:
Can't use string ("") as a HASH ref while "strict refs" in use at 103.pl line 8.

What seem to be wrong with my code?
Thanks.

Replies are listed 'Best First'.
Re: Add Data to Hash Reference
by moritz (Cardinal) on Dec 07, 2010 at 20:11 UTC
      So, if I want to construct the data structure in my example, how should I write it?

        How about

        my $test = { 'record' => { 'a' => 11, 'b' => 22 } };

        Or just:

        my $test; $test->{record}->{'a'} = 11; $test->{record}->{'b'} = 22;

        If you want to initialize $test->{record} with something (and don't rely on autovivification), initialize it with {}.

Re: Add Data to Hash Reference
by roboticus (Chancellor) on Dec 07, 2010 at 20:28 UTC

    As moritz said, you told it to create a string, not a hash. You can explicitly tell your code to create an empty hash like this:

    my $test = { record => {} };

    or you could use undef, leaving the slot empty for perl to put in a hash reference when you execute line 8.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: Add Data to Hash Reference
by shail (Initiate) on Dec 07, 2010 at 20:36 UTC
    You need to specifically create hash reference. Here is better code that prints your new hash. Note: Now dumpvar puts out data but also print another hash with undef value. I believe that is due to auto-vivification but I could be wrong.
    #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %test = { record => ' ' }; my $test = \%test; $test->{record}->{'a'} = 11; $test->{record}->{'b'} = 22; print Dumper \%test;
      This produces:

      Reference found where even-sized list expected at ./875882.pl line 7. $VAR1 = { 'record' => { 'a' => 11, 'b' => 22 }, 'HASH(0x604290)' => undef };
      If you had read the warning, you'd have realized that there's something wrong with the line

      my %test = { record => ' ' };