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

Dear Folks,, In the Perl Cookbook p. 426 there is an example of a structure like this:
$record = { NAME => "Jason", EMPNO => "132", (etc..) };
I understand that we have ref to an anonymous hash, but along the lines in the book, we want more than just one record, we want many, so the book suggests that create a %byname hash that we use this way:
$byname {$record->{NAME}} = $record;
What is the idea with this? We now have a hash of a hash, with the value of the $byname key (name) is the reference to the record ..?? How do we get many records from such a contruction? I think it is a bit confusing. Regards, ta

Replies are listed 'Best First'.
Re: Example in Cookbook of hash of hash
by ikegami (Patriarch) on Mar 26, 2010 at 17:33 UTC

    How do we get many records from such a contruction?

    By repeating the assignment with different $record.

    my %byname; for my $record ( { NAME => "Jason", EMPNO => "132", }, { NAME => "Orange", EMPNO => "133", }, ) { $byname{ $record->{NAME} } = $record; } print(Dumper(\%byname));

    In reality, your record source would be a database or LDAP or something rather than a hardcoded list.

    Update:

    Oh wait, are you asking how to access the records?

    To access one record:

    my $record = $byname{$name};

    To access each record:

    for my $name ( keys(%byname) ) { my $record = $byname{$name}; ... }

    To access each record, sorted by id:

    for my $name ( sort { $byname{$a}{EMPNO} <=> $byname{$b}{EMPNO} } keys(%byname) ) { my $record = $byname{$name}; ... }

    To check if an employee exists,

    if (exists($byname{$name})) { # yes } else { # no }
      Ikegami, thanks for your useful reply! What is going on in that for declaration? I have never seen it before like that and am confused about the position of the byname declaration, it almost looks like it part of the hash.
        Are you asking about my %byname;?
      When we make the value of $byname the reference to $record, I thought that we would get the same reference over and over again. I dont see where the reference changes, but I can see from the dump that it does in fact and work just fine.
        Guys, THANK you, especialy Ikegami for taking the time to help me. I finally figured out the for-loop by writing in this way making it more clear to me:
        my %byname; use Data::Dumper; for my $record ( { NAME => "Jason", EMPNO => "132" }, { NAME => "Orang +e", EMPNO => "133" } ) { $byname{ $record->{NAME} } = $record; }; print $byname{Orange}->{EMPNO};
Re: Example in Cookbook of hash of hash
by toolic (Bishop) on Mar 26, 2010 at 17:38 UTC
Re: Example in Cookbook of hash of hash
by planetscape (Chancellor) on Mar 26, 2010 at 21:12 UTC