I'm surprised that the adjacency list is hardcoded in many of these answers. That's the sort of thing the program should work out, so that you can scale the grid to arbitrary sizes.
I would have chosen to reference tiles by a co-ordinate pair rather than a plain numbers, so for a grid of size $p by $q, the neighbours of each tile ($x,$y) can be calculated like this:
for (my $y = 1; $y <= $q; $y++) {
for (my $x = 1; $x <= $p; $x++) {
for (my $ny=$y-1; $ny<=$y+1; $ny++) {
next if ($ny < 1 || $ny > $q);
for (my $nx=$x-1; $nx<=$x+1; $nx++) {
next if ($nx < 1 || $nx > $p || ($nx == $x && $ny == $y));
push @{$adjlist{"$x,$y"}}, [$nx,$ny];
}
}
}
}
But it's easy enough to calculate tile numbers from the co-ordinates in this loop if required. Note the optimisation where we don't bother to go into the deepest loop if we're off the top or bottom edge.
You could also do it the opposite way, looping through tile numbers from 1 to ($p*$q) and then effectively calculating the x and y position of the current tile in order to work out whether you are near an edge, but this strikes me as likely to be slower as it involves more arithmetic.