Two examples is not enough to specify your problem. I will guess that each of your array elements specifies a network connection. Your result is an equivalent connection (possibly the longest path). If so, a search of CPAN modules would be time well spent. A search for the word 'network' returns 260 modules. Initially, only consider modules in your application area. If you are lucky, you will find exactly what you need. If not, your time will probably be repaid in the form of new insight into this type of problem and it solutions.