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

Hi

I am having some trouble with hashes with a package I am writing for my company which deals with dental patients.

Basically, I have code like the sample below with patients details,thing like name, address, dob etc in the an array of hashes

Now, what I want to do is loop through each patient in turn and add the patient to a new hash key'd on thier dentists surgery ID.

$practice = {}; foreach $patient(@{$self->{patient_details}}) { $practice->{$patient->{suregery_id}} = \$patient; }

In theory, I should group all the patients with a surgery ID of 1, 2, 3 etc togther. However it isnt working. I have tried puting them in arrays, new hashes, sub routines passing back a hash, but i still cant get them all groupped together

Any ideas how I could do it?

Replies are listed 'Best First'.
Re: In a hash with hashes
by BrowserUk (Patriarch) on Jan 10, 2010 at 13:23 UTC

    You're overwriting the hash value with each new patient. Try:

    $practice = {}; foreach $patient(@{$self->{patient_details}}) { push @{ $practice->{ $patient->{suregery_id} } }, $patient; }

    It creates an array of patients for each id.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      Since BrowserUk has already provided the answer, this reply is very much BTW, but FWIW...

      In the OPed code fragment, the statement
          $practice->{$patient->{suregery_id}} = \$patient;
      repeatedly assigns (i.e., overwrites) a reference to  $patient to the hash key  $patient->{suregery_id} of the hash referenced by  $practice.

      The OPed code iterates over an array of hash references, so  $patient is already a hash reference. The statement above repeatedly assigns the LHS hash element a reference to a reference to a hash, which is probably even less what weezer_316 wanted! (Again, not that it matters much at this point.)

      The code is at work, I'm at home, but I think your a genius! Thats utterly obvious and ive totally missed it. Thanks alot!

Re: In a hash with hashes
by apl (Monsignor) on Jan 10, 2010 at 13:36 UTC
    Are you certain you want the hash based on suregery_id, or do you mean $suregery_id?

      SugeryID. The data is being pulled from a database and the rows title is SurgeryID so ill keep it as it is.