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?

$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.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."
  • Comment on Re^3: How do I reverse the order of the first and last word of a string?
  • Download Code

Replies are listed 'Best First'.
Re^4: How do I reverse the order of the first and last word of a string?
by vrk (Chaplain) on Mar 11, 2007 at 07:23 UTC

    You may want to fix that to properly handle punctuation and capitalization:

    $_ = 'This is the word.'; $_ =~ s[(^\w+)(\s.*\s)(\w+)([[:punct:]]?)$][\u$3$2\l$1$4]; print

    --
    print "Just Another Perl Adept\n";

Re^4: How do I reverse the order of the first and last word of a string?
by Not_a_Number (Prior) on Mar 11, 2007 at 12:07 UTC
    $s = 'Two words'; $s =~ s[(^\S+)(\s.*\s)(\S+$)][$3$2$1]; print $s; #Two words

    Oops! ;-)

      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.