in reply to Re^2: 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?

That's a respectable attempt you've made. Like you said, the problem is that you're only swapping the first and the second word. You should also try to match the stuff between two words, and suddenly it's not longer impossible to match the first and the last word.

If you try

s/(\w+)(.*)(\w+)/$3$2$1/
you'll see that you'll have some trouble with greediness of the middle match: the "last word" will match too little: I expect it to match just the last letter.
s/(\w+)(.*?)(\w+)/$3$2$1/
is the other extreme, and you'll match too little.

I can think of two solutions:

  1. Use the (latter) non-greedy match, but anchor that far side to the end of the string:
    s/(\w+)(.*?)(\w+)$/$3$2$1/
    or
    s/(\w+)(.*?)(\w+)(\W*)$/$3$2$1$4/
  2. Require there's a word boundary just in front of the last match, and match greedily.
    s/(\w+)(.*)\b(\w+)$/$3$2$1/
All untested, but I have faith. :)