#! perl -slw use strict; use Data::Dump qw[ pp ]; my @array = (['A','B'],['C','D'],['A','C'],['E','F'],['F','G']); my @buckets; for( sort { $a->[0] cmp $b->[0] } @array ) { my( $x, $y ) = @$_; my $added = 0; for my $bkt ( @buckets ) { if( exists $bkt->{ $x } or exists $bkt->{ $y } ) { undef @{ $bkt }{ $x, $y }; ++$added; } } push @buckets, { $x, undef, $y, undef } unless $added; } $_ = [ sort keys %$_ ] for @buckets; pp \@buckets; __END__ C:\test>1017261-2 [["A", "B", "C", "D"], ["E", "F", "G"]]