Background: I have some results from clustering of biological data which shows the number of shared connections between clusters. What I am trying to accomplish is to reduce this list of pairwise relationships to unique sets of identifiers based on shared connections. The data format is straightforward, it has three columns that show 1) cluster ID *i*, 2) cluster ID *j*, and 3) the number of shared connections between *i* and *j*. A sample of the actual data is in the code below. 

Here is the code I have so far:

```
#!/usr/bin/env perl

use v5.10;
use strict;
use warnings;

my %linkage;

while (my $line = <DATA>) {
    my ($i, $j, $score) = split /\s+/, $line;
    if (exists $linkage{$i} && not exists $linkage{$j}) {
        push @{$linkage{$i}}, $j;
    }
    elsif (exists $linkage{$j}) {
        push @{$linkage{$j}}, $i;
    }
    else {
        $linkage{$i} = [$j];
    }
}

for my $key (sort keys %linkage) {
    say join "\t", $key, join ",", @{$linkage{$key}};
}

__DATA__
CL21    CL9     2628
CL36    CL33    2576
CL29    CL59    2384
CL65    CL36    2318
CL65    CL47    2151
CL32    CL17    2147
CL21    CL31    2136
CL23    CL17    2092
CL94    CL59    2091
CL16    CL11    2088

```

This produces:

```
CL16    CL11
CL21    CL9,CL31
CL23    CL17
CL29    CL59
CL32    CL17
CL36    CL33,CL65
CL65    CL47
CL94    CL59

```

There are two issues here that I would like some assistance/advice in solving. The first issue is that there are still duplicate entries in the second column (i.e., CL17), which I would like to reduce. The second issue is that an identifier should be added to an existing grouping if it has been seen before, instead of starting a new group (i.e., CL65). Note that I am not keeping the values in the output with this example, but you can see the input is sorted in descending order, so it makes sense (to me) to build up the groupings in this fashion based on what has been seen.

Desired output:

```
CL16,CL11
CL21,CL9,CL31
CL23,CL17,CL32
CL29,CL59,CL94
CL36,CL33,CL65,CL47

```

I hope it is clear from this desired output that each line should be a unique set (and the tab was added in the code/output above to make it easier to see the problems). If a question like this has been asked before, or illustrated on some other page, please let me know (and I apologize in that case).