Search code examples
perlhashmultiple-valueperl-data-structures

How can I store multiple values in a Perl hash table?


Up until recently, I've been storing multiple values into different hashes with the same keys as follows:

%boss = (
    "Allan"  => "George",
    "Bob"    => "George",
    "George" => "lisa" );

%status = (
    "Allan"  => "Contractor",
    "Bob"    => "Part-time",
    "George" => "Full-time" );

and then I can reference $boss("Bob") and $status("Bob") but this gets unwieldy if there's a lot of properties each key can have and I have to worry about keeping the hashes in sync.

Is there a better way for storing multiple values in a hash? I could store the values as

        "Bob" => "George:Part-time"

and then disassemble the strings with split, but there must be a more elegant way.


Solution

  • This is the standard way, as per perldoc perldsc.

    ~> more test.pl
    %chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
               "Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );
    
    print $chums{"Allan"}{"Boss"}."\n";
    print $chums{"Bob"}{"Boss"}."\n";
    print $chums{"Bob"}{"Status"}."\n";
    $chums{"Bob"}{"Wife"} = "Pam";
    print $chums{"Bob"}{"Wife"}."\n";
    
    ~> perl test.pl
    George
    Peter
    Part-time
    Pam