Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

hello iv just coded with perl for a few days and my teacher are asking me to do as the title say "Print the string out in alternating upper and lowercase letters LiKe tHiS." but i have no idee on how to do it, pls help
  • Comment on Print the string out in alternating upper and lowercase letters LiKe tHiS.

Replies are listed 'Best First'.
Re: Print the string out in alternating upper and lowercase letters LiKe tHiS.
by karlgoethebier (Abbot) on Jan 25, 2015 at 19:46 UTC

      I rather like one of the SO regex solutions, but without the odd-string-length problem:

      c:\@Work\Perl>perl -wMstrict -le "my $s = 'like this'; print qq{'$s'}; ;; $s =~ s{ (.)(.?) }{\U$1\L$2}xmsg; print qq{'$s'}; " 'like this' 'LiKe tHiS'


      Give a man a fish:  <%-(-(-(-<

        Odd length is only a problem if you have to change the last character. For this case we can use:
        use strict; use warnings; my $string = 'athis'; print $string =~ s/(.)(.)/$1.uc$2/egr;
        Bill
Re: Print the string out in alternating upper and lowercase letters LiKe tHiS.
by Anonymous Monk on Jan 25, 2015 at 19:54 UTC
    $ perl -E 'say map { $c++ % 2 ? lc : uc } split //, "like this"' LiKe tHiS
Re: Print the string out in alternating upper and lowercase letters LiKe tHiS.
by Anonymous Monk on Jan 25, 2015 at 19:28 UTC
    Go to perlfunc and find what you're looking for
      thnx will did that and i think iv found a solution :D
Re: Print the string out in alternating upper and lowercase letters LiKe tHiS.
by hdb (Monsignor) on Jan 26, 2015 at 12:34 UTC

    "LiKe tHiS" is NOT alternating upper and lowercase letters, there is a lower case "e" followed by a lower case "t". Or is there an upper case blank inbetween?


      perl -e "print map { $c++ %2 ? chr $_^' ' : chr $_ } unpack 'C*', $ARG +V[0]" "like this"
      suffers the same problem of whitespace but is less redable... ;=)

      L*
      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      A more robust solution if you like:
      perl -CO -Mutf8 -E 'say map { /\P{Cased}/ ? $_ : $c++ % 2 ? lc : uc } "comme ça" =~ /(\X)/g'
      Of course, at this point we should perhaps consider ucfirst and fc...
        (a typo; /^\P{Cased}/, of course, or else it can find these annoying combining marks...)