use Graph; use strict; use warnings; my @sets = ( [qw(0)], [qw(0 1)], [qw(0 1 2)], [qw(1 2 3)], [qw(4 5 6)], ); my $gr = new Graph undirected => 1, unionfind => 1; for my $set ( @sets ) { @$set == 1 and $gr->add_vertex( $set->[0] ); @$set <= 1 and next; $gr->add_edge( $set->[$_-1], $set->[$_] ) for 1 .. $#{$set}; } for my $set ( $gr->connected_components ) { print "( @$set )\n"; }