use warnings; use strict; my @my_arr=( [1, 11, 0, 0], [12, 109, 0, 0], [16, 1, 16, 0], [14, 14, 2, 0], [45, 16, 5, 4] ); my ($index1, $index2) = (5, 4); #used 1-based index for easy communication while (1) { last if $index1 > 5 || $index1 < 1 || $index2 > 4 || $index2 < 1; print $my_arr[$index1 - 1][$index2 - 1], "\n"; $index1 = $my_arr[$index1 - 1][$index2 - 1]; $index2 --; }