my @merged = mapAdjPairs{ if ($a->[2] eq 'S') { # $a is a start point if ( $b->[2] eq 'E' and $a->[0]{X} == $b->[0]{X} # Introduce FP fudge factor if needed and $a->[0]{Y} == $b->[0]{Y} ) { # $b is and end and we found a coincident end/start pair push @{ $b->[1] }, @{ $a->[1] }[1.. $#{$a->[1]} ]; return; # we merged two sections so don't add to result } else { # We have a start point and didn't merge so add to the results return $a->[1]; } } return; } @ends, $ends[0]; # Note:Repeat first element last to complete cycle