It will be be good to see what you have tried in first place
but I won't stop with that
Here is one way of doing it
input hash
my %hash= (
Group1 => 'ATG1,ATG2,ATG4,ATRG7',
Group2 => 'ATG1,ATG9',
Group3 => 'FYCO1,LSM2',
Group4 => 'ATG1,MAM2',
Group5 => 'LSM2',
);
code
use strict;
use warnings;
use Data::Dumper;
my %hash= (
Group1 => 'ATG1,ATG2,ATG4,ATRG7',
Group2 => 'ATG1,ATG9',
Group3 => 'FYCO1,LSM2',
Group4 => 'ATG1,MAM2',
Group5 => 'LSM2',
);
my (%newhash,$i,%combinegroups,%splittedhash);
foreach my $key (keys %hash){
my @values ;
if($hash{$key} =~ /,/){
@values = split(/,/,$hash{$key}) ;
$splittedhash{$key} = [ @values ];
}else{
push(@values,$hash{$key});
$splittedhash{$key} = [ @values ];
}
if(++$i == 1) {
my @newvalues;
push (@newvalues,$key) for(0..scalar @values);
@newhash{@values} = @newvalues;
}else{
foreach (@values){
if(exists $newhash{$_}){
$combinegroups{$newhash{$_}.":".$key}++;
}else{
$newhash{$_} = $key;
}
}
}
}
foreach my $key (keys %combinegroups){
my ($firstgroup,$secondgroup) = split(/:/,$key);
my %unique;
@unique{@{$splittedhash{$firstgroup}},@{$splittedhash{$secondgroup
+}}} = ();
$hash{$firstgroup} = join(',',keys %unique);
@{$splittedhash{$firstgroup}} = keys %unique;
delete $hash{$secondgroup};
}
print "FINAL HASH\n",Dumper \%hash;
output
FINAL HASH
$VAR1 = {
'Group4' => 'ATG9,ATG2,ATRG7,ATG4,ATG1,MAM2',
'Group5' => 'FYCO1,LSM2'
};
but, this code will behave wrongly for a condition, if value1 in group1 match with group2 and at the same time value2 in group1 match with group3.
might have some other bugs also
but to start with, this code will work, the rest is upto you
I haven't worried about efficiency in my code, it can be written even more effectively!, but this will work for your this case if a value from 1 group (key) is found as a value from another group then I want to combine the values from both of those groups into a single set of values
Vivek
-- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
|