You appear to be doing graph theory. You might want to check out the 'Graph' module on CPAN. It's possible your bigger problem (which you seem to want to solve by merging edges to form trails) is an instance of a more general problem solved by one of the supplied algorithms or methods.
e.g. there is a connected_components method which looks like it might be related to your problem (perhaps not, depending on whether the ordering in your problem is an artifact of your example or not).