Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 965
paxdiablo Avatar asked Oct 10 '08 07:10

paxdiablo


People also ask

Can a hash have multiple values?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

How do I add multiple values to a key in Perl?

You could try pushing each value onto a hash of arrays: my (@gene, @mrna, @exon, @cds); my %hash; push @{ $hash{$gene[$_]} }, [$mrna[$_], $exon[$_], $cds[$_] ] for 0 .. $#gene; This way gene is the key, with multiple values ( $mrna , $exon , $cds ) associated with it.

How does Perl store data in hash?

Perl for Beginners: Learn A to Z of Perl Scripting Hands-on A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..

How do I append a hash in Perl?

To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value. When inverted, you end up with a hash that has many values for the same key.


1 Answers

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 
like image 175
Vinko Vrsalovic Avatar answered Sep 30 '22 07:09

Vinko Vrsalovic