my $lineregex = qr{}ms; $input =~ s{ ( # $1 is first 3 lines $line $line $line ) ( # $2 is second 3 lines $line $line $line ) ( # $3 is third 3 lines $line $line $line ) }{$2$3$1}gx;