my @subg; for my $component (0 .. @subgraphs - 1) { $subg[$component] = Graph::Undirected->new; for my $i (0 .. $#a) { $subg[$component]->add_edge($a[$i], $b[$i]) if grep $_ eq $a[$i], @{ $subgraphs[$component] }; } }