sangramjit basu sangramjit basu - 6 months ago 21
Perl Question

unique value in hash while merging their keys

I have a file with tab separated columns like this:




Now I split these into two arrays (one for each column values) then convert them into hashes but I want to remove the duplicates (here its TR2) while merging their right column values...something like this TR2=>P0C133, is it possible?? is there any function to do it in perl??

if($s_arr[$i] eq $s_arr[$i+1])
{ push(@temp,$idx_arr[$i]); }

if(@temp eq "")
{ $s_hash{$s_arr[$i]}=$idx_arr[$i]; }

this is code I've written where @s_arr is storing left column values and @idx_arr is storing right column value


You can avoid using two arrays and perform what you want in one fell swoop treating the left-side value as the hash key and making it an array reference, then pushing the right-side values that correlate with that key onto that aref:

use warnings;
use strict;

use Data::Dumper;

my %hash;

while (<DATA>){
    my ($key, $val) = split;
    push @{ $hash{$key} }, $val;

print Dumper \%hash;

TR1 P0C134
TR2 P0C133
TR2 P0C136


$VAR1 = {
    'TR1' => [
    'TR2' => [