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.
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.
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.
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..
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With