#!/usr/bin/env perl use strict; use warnings; my @strings = qw(AGCT AGGT GG AGCT); my %uniques; $uniques{shift @strings}++ while @strings; my @slots; while (my $i = each %uniques) { push @{$slots[length $i]}, $i; delete $uniques{i}; } my $master = join (':', @{pop @slots}); while (@slots) { my @nomatch = grep {index ($master, $_) < 0} @{pop @slots or []}; $master .= ':' . join (':', @nomatch) if @nomatch; } # answer $master =~ s/:/\n/g; print $master;