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

Dear Monks
What I'm trying to do is take a string and typecase, or make the first letter of every word a capital. I came up with the below solution. Since I don't get to use regex as often as I would like, I was wondering if there might be a more graceful way of doing this.
my $data = <DATA>; $data =~ s/\b(\w{1})(\w*)/\u$1\L$2/g; print $data; __DATA__ balh balh aLhKKjal dfjsdlkj IUfJ
Thank you for any input.
s;;5776?12321=10609$d=9409:12100$xx;;s;(\d*);push @_,$1;eg;map{print chr(sqrt($_))."\n"} @_;

Replies are listed 'Best First'.
Re: Regex Typecase
by merlyn (Sage) on Aug 14, 2007 at 01:26 UTC
      Thankyou, I knew there was a better way.
      s;;5776?12321=10609$d=9409:12100$xx;;s;(\d*);push @_,$1;eg;map{print chr(sqrt($_))."\n"} @_;
Re: Regex Typecase
by wind (Priest) on Aug 14, 2007 at 02:03 UTC
    Or if you favor a style using functions:
    $data =~ s/(\w+)/ucfirst lc $1/eg;

    I'd personally stick with merlyn's example though.

    - Miller

Re: Regex Typecase
by Your Mother (Archbishop) on Aug 14, 2007 at 06:05 UTC

    Quick aside for the search engines. You mean "titlecase," not "typecase." Prepositions and articles are generally not included in English so you'd want to do a hash based lookup : substitution for that. Also, given problematic abbreviations (pH) and propernames (McPerl) it's not possible to programmatically titlecase perfectly but you can get pretty close.

      The library rules for title case are even more complicated than that. I learned that you capitalize the first and last words, even if they ARE prepositions or articles. You're right in that the edge cases like apostrophes and multiple capitals (e.g., "McDonald's") are annoyingly complicated to get right.

      For my website, I have a "turn filenames into titles" function. For example, a-sunrise-to-remember.jpg becomes "A Sunrise to Remember" which uses a small canned list of the most common prepositions and articles (including a few in Spanish). Every once in a while, I find I have to add yet another special case.

      [ e d @ h a l l e y . c c ]