Hi Rob, This works and looks much more simpler. Thanks, i love it.
--budhi On Fri, Jan 11, 2013 at 1:00 AM, Rob Dixon <rob.di...@gmx.com> wrote: > On 10/01/2013 10:01, budi perl wrote: > >> Hi, >> >> I have this following hash: >> >> #!/usr/bin/perl >> # >> use strict; >> use Data::Dumper; >> >> my %MYROUTES = ( >> "ROUTE-252" => { >> # src => dest >> 427 => "ABEP", >> "ABEP" => 441, >> 441 => 427, >> 427 => 444, >> 444 => "MGWQ", >> "MGWQ" => "CDEF" >> }, >> >> "ROUTE-432" => { >> "AAA" => "BBB", >> "BBB" => "CCC", >> "CCC" => "DDD", >> "XXX" => "YYY", >> "YYY" => "ZZZ" >> } >> ); >> >> print Dumper %MYROUTES; >> >> __END__ >> >> Expected results: >> >> ROUTE-252: 427 - ABEP - 441 - 427 - 444 - MGWQ - CDEF >> ROUTE-432: Error: can not follow the route! >> >> or if possible can be more specific on how many link founds: >> Error, some path is missing: >> ROUTE-432: AAA - BBB - CCC -DDD >> ROUTE-432: XXX - YYY -ZZZ >> >> I put data in order for brevity, actual data may not. >> >> Can someone shed some light how to find head then follow the path as >> above? >> > > This calls for a proper module that has been thoroughly tested. The > program below uses Graph::Directed. Beware that it does no checks for > things like cyclic links, but it does print the path to /all/ end points > starting at each source. > > HTH, > > Rob > > > use v5.10; > use warnings; > > use Graph::Directed; > > my %routes = ( > "ROUTE-252" => { 427 => 444, 441 => 427, 444 => "MGWQ", ABEP => 441, > MGWQ => "CDEF" }, > "ROUTE-432" => { AAA => "BBB", BBB => "CCC", CCC => "DDD", XXX => "YYY", > YYY => "ZZZ" }, > ); > > while (my ($label, $edges) = each %routes) { > > my $graph = Graph::Directed->new; > > while (my ($start, $end) = each %$edges) { > $graph->add_edge($start, $end); > } > > my @sinks = $graph->sink_vertices; > for my $source ($graph->source_vertices) { > for my $sink (grep $graph->is_sink_vertex($_), $graph->all_successors($ > **source)) { > say "$label: ", join ' - ', $graph->path_vertices($source, $sink); > } > } > } > > **output** > > ROUTE-252: ABEP - 441 - 427 - 444 - MGWQ - CDEF > > ROUTE-432: AAA - BBB - CCC - DDD > ROUTE-432: XXX - YYY - ZZZ > >