in reply to Re^4: How do I reverse the order of the first and last word of a string?
in thread How do I reverse the order of the first and last word of a string?
The split and join I'm sure you understand. I suspect the bit you find interesting is the "swap without temporary" - an old assembly language trick. In situations where there weren't enough registers to use one for temporary storage when swapping two registers and the time cost of going off chip was great this trick could be used to peform the exchange. The three xors sort of slide the bits from each regiser through each other. Consider (note binary values - this is not Perl):
a = 0011 b = 1010 a = a ^ b (a now contains 1001) b = a ^ b (b now contains 0011 - a's original contents) a = a ^ b (a now contains 1010 - b's original contents)
In the example code two strings get swapped using the technique. However if the strings are different lengths then the shorter string will end up with trailing null characters. The substitution strips the nulls. A tr could have been used instead, but substitutions are more often used in general so a better thing for the OP to be made aware of.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: How do I reverse the order of the first and last word of a string?
by blazar (Canon) on Mar 11, 2007 at 11:16 UTC | |
by jeanluca (Deacon) on Mar 11, 2007 at 11:36 UTC | |
by blazar (Canon) on Mar 11, 2007 at 12:14 UTC | |
|
Re^6: How do I reverse the order of the first and last word of a string?
by jeanluca (Deacon) on Mar 11, 2007 at 16:24 UTC | |
by jonadab (Parson) on Mar 11, 2007 at 16:44 UTC | |
by jeanluca (Deacon) on Mar 11, 2007 at 17:05 UTC |