sub returnGreaterTranspose {
  @digits = split('',$_[0]);
  $max = 0;
  for($i=$#digits;$i>=0;$i--){
    $digit = $digits[$i];
    if ($max > $digit) {
      @firstDigits = @digits[0..($i-1)];

      @lastDigits = @digits[$i..$#digits];
      @lastDigits = sort(@lastDigits);

      foreach $d (@lastDigits) {
        if ($d > $digit) {
          splice(@firstDigits, $i,0,$d);
          $digit = $max;
        } else {
          push(@firstDigits, $d);
        }
      }

      return join("",@firstDigits);

    }
    if ($max < $digit) {
      $max = $digit;
    }
    
  }
}

print returnGreaterTranspose(7585);
print "\n";
print returnGreaterTranspose(7567);
print "\n";
print returnGreaterTranspose(7576);
print "\n";
