perl - How to get multiple values of Hash based on key -
i getting data csv , storing in data in hash.from there want provide key , based on key want values of hash.there can duplicate key that's want values of hash .
for ex :
**specid note_text** 300000111166 ldpe bottle/jar 300000111166 poly-lined steel drum 300000057768 amber glass bottle/jar
now if give key : 300000111166
i should values : ldpe bottle/jar,poly-lined steel drum.how can done.
use array references values of hash. when going on input, push
values hash instead of assigning them. when retrieving hash values, remember hash value must dereferenced see contents.
while (<fh>) { ($key,$value) = split /\t/; push @{$hash{$key}}, $value; } ... foreach $key (keys %hash) { print "values $key: "; print join(",", @{$hash{$key}}), "\n"; }
use multi-dimensional hash. advantage of approach duplicate values won't printed twice (or disadvantage, depending how want handle duplicate values)
while (<fh>) { ($key,$value) = split /\t/; $hash{$key}{$value}++; } ... foreach $key (keys %hash) { print "values $key: "; print join(",", keys %{$hash{$key}}), "\n"; }
use tried-and-true solution problem: the tie::hash::multivalue
module:
use tie::hash::multivalue; tie %hash, 'tie::hash::multivalue'; while (<fh>) { ($key,$value) = split /\t/; $hash{$key} = $value; } ... foreach $key (keys %hash) { print "values $key: "; print join(",", @{$hash{$key}}), "\n"; }
Comments
Post a Comment