in reply to building a hash from a database

(update First of all, $rowdata contains a hashref, that's not the same as %rowdata. You have to use $rowdata->{'id'} instead of $rowdata{'id'}. And now, continuing with the rest of the story, assuming that is fixed...)

use strict;!!!

You're doing this in two steps. As a result of the line

$hash{$rowdata->{'id'}} = $rowdata->{'id'};
$hash{$rowdata->{'id'}} has an integer for a value, and you're using that as a symbolic reference to a new hash.

use strict would have prevented you from doing that.

I think you can change the code to do what you want, by changing that line to

$hash{$rowdata->{'id'}} = { '' => $rowdata->{'id'} };

Replies are listed 'Best First'.
Re^2: building a hash from a database
by bfdi533 (Friar) on May 02, 2006 at 15:42 UTC

    Hmmm... I must admit (if it is not obvious) that there a number of things about hashes that I do not understand.

    What do you mean by symbolic reference to a new hash?

    I have made the change that you suggested and now I get this:

    $VAR1 = { '' => { '' => undef } };

    What I need to be able to do later is to reference the has created like this:

    foreach $key (keys %hash) { print $key, $key{'fname'}, $key{'lname'}, "\n"; }
      You're still making the mistake of confusing $rowdata->{$field} with $rowdata{$field}. I fixed that in my code with an update, I admit I only spotted that later. So there was more than one thing wrong with the code. :)

      What do you mean by symbolic reference to a new hash?
      Well, first of all, you're setting the value of $hash{$id} to, say, 1. And then you set $hash{$id}{'fname'} to "foo". As a result, you really are trying to set $1{'fname'} to "foo".

      What I need to be able to do later is to reference the has created like this:
      foreach $key (keys %hash) { print $key, $key{'fname'}, $key{'lname'}, +"\n"; }
      No way, but you will be able to use
      foreach $key (keys %hash) { print $key, $hash{$key}{'fname'}, $hash{$key}{'lname'}, "\n"; }

        OK, ok, ok. I think I finally understand, finally.

        I had tried that change from earlier and it did not make any difference at that time as I had not accounted for/changed the code to deal with the hashrefs correclty (->). I have now made both changes and it does exactly what I wanted it to.

        I have learned much more about hashes than I realized I did not know.

        Thanks (and thanks for the patience).