This is quite simple:
$order = 4213;
$before = 9876;
@ordered[split(//, $order)] = split(//, $before);
$after = join '', @ordered;
This turns both strings of digits into lists of single digits, then uses the list defining the order to fill an array slice with the number in need of ordering. When this is printed, you get them out in the right order, the first element of @ordered is empty though, but in this case that doesn't matter too much. Remember also that this will break with more than nine digits, or ten if you allow for '0' to be used when ordering (it comes before 1).