Why did the midwife tie a red thread on the hand of the fetus that poked out?
Seforno (to 38:27): It was to identify which came out first. 1 Moshav Zekenim, citing R. Yehudah ha'Chasid - Even though in any case, he is not [Yehudah's] Bechor, the custom was that the Bechor of a second wife received a field designated in her Kesuvah, for an extra portion. Also, it is relevant to redeem him from a Kohen for five Shekalim, which depends on Peter Rechem. Twins are prone to get mixed up. 2
Ohr ha'Chayim: She had Ru'ach ha'Kodesh and tied it, without knowing why. She [assumed and] said that he will come out first; the thread proved that it was not so.
Perhaps she suspected that it was a Divine Siman that he stuck out his hand, just like Yaakov came out holding Esav's heel (refer to 25:26:1:2 et. al). The Bechor was called Peretz because he overtook the one who stuck out his hand (PF)!
It was already known that she would have twins; Refer to 38:25:4:1, 38:25:4.1:1; 38:27:151:1. (She assumed that the one who stuck out his hand to come out first. Perhaps she tied it now, for after birth she will be busy cutting the umbilical cord.... - PF)
Peter Rechem depends on birth, i.e. when the head or majority leaves. It would have sufficed to make a Siman on one baby after full birth! (PF)
QUESTIONS ON RASHI
Rashi writes: "'Va'Yiten Yad' - One of them put out his hand outside." What is Rashi explaining?
Gur Aryeh: An unborn child cannot "extend his hand" on purpose (in the same sense that an adult would). It simply means that his hand emerged from the womb.
Rashi writes: "'Va'Yiten Yad' - ... After she tied the red string on his hand, he brought it back." What is Rashi explaining?
Gur Aryeh: Why does the verse say, 'he put [out],' rather than using the term 'born'? It must be that this was not yet true birth, for he then pulled back his hand.