#!/usr/bin/perl use strict; use warnings; $\ = "\n"; $_ = 9876543210; my $n = 0; # to limit output $n++ < 12 or exit while print, s/.*\K (.) (?=(.)(??{$1 < $2 and 'x'}) (.*) (.)(??{$1 < $4 and 'x'}) (.*) / $4 . reverse $3.$1.$5 /xe