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

I appreciate the help as I am new to Perl and programming in general.
  • Comment on Re^2: How do I reverse the order of the first and last word of a string?

Replies are listed 'Best First'.
Re^3: How do I reverse the order of the first and last word of a string?
by GrandFather (Saint) on Mar 10, 2007 at 22:31 UTC

    Welcome to the Monastery. Generally you will find that you get the most help when you show that you have done some work and demonstrate that you are not just looking for someone else to do your homework for you.

    I suspect that if you hand in the code I gave above as a homework answer your teacher will either not believe that you wrote it, or will think that you are a smart arse and shouldn't be in the course.

    However if you read the documentation for split and join you may find that you can come up with a more acceptable solution for yourself.


    DWIM is Perl's answer to Gödel
      Thats an impressive example GrandFather! do you also have some links/docs to help me understand your example a little bit better ?

      Thnx
      LuCa

        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.


        DWIM is Perl's answer to Gödel