use warnings; use strict; use Data::Dump; my @AoA = ( [11,29, 10,25], [15,35, 11,29], [15,15, 11,21], [10,25, 11,21], [15,35, 21,39], [25,40, 21,39], [21,11, 25,10], [15,15, 21,11], [35,35, 29,39], [29,39, 25,40], [35,15, 29,11], [25,10, 29,11], [40,25, 39,29], [35,35, 39,29], [39,21, 40,25], [35,15, 39,21], ); $"=","; my %neighbor; for ( @AoA) { my ($a,$b)= ("@$_[0,1]", "@$_[2,3]") ; push @{$neighbor{$b}}, $a; push @{$neighbor{$a}}, $b; }; #dd \%neighbor; #--- init my $next; my @path; my ($last,$current)=("11,29","10,25"); # start push @path, $last, $current; delete $neighbor{$last}; while ( %neighbor) { my $a_neighbors = delete $neighbor{$current}; die "Data corrupt: $current has no more neighbors" unless $a_neighbors; ($next) = grep { $_ ne $last } @$a_neighbors; ($last,$current)=($current,$next); push @path, $current ; } #dd \@path; my @flat= map { split ",", $_ } @path; print join ",", @flat;