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

How do I go about converting every word of a line
to lowercase, with the first character in uppercase,
and then convert the last word of the line to uppercase?

Thanks, from a novice.

Replies are listed 'Best First'.
Re: Mixing the case of a line
by tadman (Prior) on Nov 16, 2001 at 01:39 UTC
    You use the \u/\U and \l/\L operators in conjunction with a regex. \u uppercases the next character, \U to all following characters. Likewise with \l, except for lower-case. You can stack them too, like \u\L, which will make the next character upper-case, but all subsequent ones lower-case.
    $_ = ""; s/\b(\w+)\b/\u\L$1/g; s/(\w+\s*)$/\U$1/g;
    Thus, "tHis is a TEST line oF,teXT" will become "This Is A Test Line Of,TEXT". If you have a lot of debris, like brackets, commas and whatnot, you might have to tweak this a bit to better match your definition of "word". Do you want it to be "Free-Lance" or "Free-lance"?

      Just to further highlight some of the things tadman mentions: Strings may have punctuation after the final word and some words may have an apostrophe or hyphen(s). You can tune a regex to grab whatever you consider to be words in a s/// operation and apply the \u and \L escapes as needed in the replacement. Here is one potential solution:

      #!/usr/bin/perl -w use strict; while(<DATA>){ s/\b(\w+(?:['-]\w+)*)\b/\L\u$1/g; s/(\w+(?:['-]\w+)*[\W\s]*)$/\U$1/; print; } __DATA__ tHis IS just one exAMPle, note: some STRINGS haVe apOStrophEs or hyPHens, and perhaps faulty punctuation or trailing elipsis ... doN't SETTLE for over-THE-counter sOLutions! !! including this one.

      I hope this isn't homework, but if it is please do yourself a favor and read up on regexen (perlre) and the various case-functions (uc, lc, ucfirst, and lcfirst), and their equivalent double-quoted string escapes (perlop, in the section "Quote and Quote-like Operators").

Re: Mixing the case of a line
by blakem (Monsignor) on Nov 16, 2001 at 01:42 UTC
    Depending on your definition of "word" and whether or not you have multiple spaces between "words" something like this might work:
    #!/usr/bin/perl -wT use strict; my $string = 'abc def GHI JkLMno pQrSTUv'; my @words = map {ucfirst(lc($_))} split(' ',$string); # Abc Def, etc. +.. $words[-1] = uc($words[-1]); # PQRSTUV my $newstring = join(' ',@words); # back together print "$newstring\n"; __END__ =head1 OUTPUT Abc Def Ghi Jklmno PQRSTUV
    You should probably read about uc, lc, and ucfirst.

    -Blake

      Thanks to you all. It had me beaten how to uppercase the last word of a line, which may be hyphenated as in Smith-Jones.
      It is not homework but part of my genealogy, where I get Birth, Death, Marriage certificates forwarded electronically, but they are all uppercase text.
      Thanks also for the direction and reference material