$s = 'This is the word';
$s =~ s[(^\S+)(\s.*\s)(\S+$)][$3$2$1];
print $s;
word is the This
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [d/l] |
$_ = 'This is the word.';
$_ =~ s[(^\w+)(\s.*\s)(\w+)([[:punct:]]?)$][\u$3$2\l$1$4];
print
| [reply] [d/l] |
Nope.
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] |
$s = 'Two words';
$s =~ s[(^\S+)(\s.*\s)(\S+$)][$3$2$1];
print $s;
#Two words
Oops! ;-) | [reply] [d/l] |
The OP asked for help, not a perfect solution. S'always good to leave a little something for them to do themselves. It encourages people to try and understand the help provided, rather than just using it verbatim.
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] |
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:
- 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/
- 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. :) | [reply] [d/l] [select] |