use strict; use warnings; use Graph; @ARGV = ('b,c|a', 'a,c|d', 'd,e|b') unless @ARGV; my %HoA; foreach ( @ARGV ) { m/^([a-z])[,]([a-z])[|]([a-z])$/ ; push @{$HoA{$1}}, $2; } print "\n===========\@HoA=====\n"; print "from->to\n"; while (my ($key, $values) = each %HoA) { print $key, "=> [", join(',', @$values), "]\n"; } my $g = Graph->new( undirected => 1 ); for my $src ( keys %HoA ) { for my $tgt ( @{ $HoA{$src} } ) { $g->add_edge($src, $tgt); } } my @subgraphs = $g->connected_components; my @allgraphs; for my $subgraph ( @subgraphs ) { push @allgraphs, {}; for my $node ( @$subgraph ) { if ( exists $HoA{ $node } ) { $allgraphs[-1]{$node} = [ @{ $HoA{$node} } ]; } } } print "----connected components------------"; use YAML; print Dump \@allgraphs; -------------OUTPUT---------------- ===========@HoA===== from->to a=> [c] b=> [c] d=> [e] ----connected components--------------- - a: - c b: - c - d: - e