my $num = shift; my $firstlen = int(length($num)/2 + .5); my $backlen = length($num) - $firstlen; my $first = substr($num, 0, $firstlen); my $closest = 0; for (1..2) { my $new = $first . substr(reverse($first), -$backlen); $closest = $new if abs($new - $num) < abs($closest - $num); $first += $num <=> $closest; } print "Closest palindrome to $num is $closest\n";