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

I know this is a big newbie regexp question, but I am reading in from a text file where all of the names are in all capitals e.g. JOE SMITH. I want to change it to Joe Smith with something like:
($firstName,$lastName) =~ tr/^?[A-Z]/[a-z]/;
But, I know that is not right. I could just do a simple character by character deal on the strings; but I am trying to blossom from my newbie status. Your wisdom is appreciated.

Jeremy

Replies are listed 'Best First'.
Re: Changing to Lowercase Except the First Letter
by runrig (Abbot) on Jan 30, 2001 at 02:38 UTC
    There are modules for this. What about "MacDonald" and other such names? See modules starting with Lingua::EN. (e.g. NameCase, NameParse (Although it must be said that NameParse IS rather slow, so its not very good for frequent processing of large datasets))

    The simple solution, though, as you ask for it, is:
    my $str = "ABC DEF"; $str =~ s/(\w+)/\u\L$1/g;
Re: Changing to Lowercase Except the First Letter
by jynx (Priest) on Jan 30, 2001 at 02:19 UTC

    In this case it's probably best to let perl do the task for you using the lc and ucfirst functions. For an example:
    $firstname = ucfirst lc $firstname; $lastname = ucfirst lc $lastname;
    Think for a little bit and you can probably think of a loop to do this if you have a few values you need to do operate on.

    HTH,
    jynx

Re: Changing to Lowercase Except the First Letter
by tune (Curate) on Jan 30, 2001 at 10:14 UTC
Lingua::EN::NameCase
by meonkeys (Chaplain) on Jan 30, 2001 at 08:58 UTC
    I would agree with runrig that a module like Lingua::EN::NameCase would be the way to go. I would recommend, however, the following: If you are casing names for users on a website, do it ONCE when they first enter their name. Allow them to edit their names if the casing did not turn out perfectly. The problem is not that the module is badly written, but some people prefer a different casing.

    For example, some prefer deSalvo, while others prefer DeSalvo. Best to let them maintain their own name (if that's what you're doing), right?
Re: Changing to Lowercase Except the First Letter
by dmckee (Scribe) on Jan 30, 2001 at 15:26 UTC
    In the interests of TMTOWTDI, why not try something like:
    $capped=$string|" ";
    (I think | is the right operator: it may be ^ instead.)
    Again, it's not a wonderful piece of code, and there are better ways of doing it (the proper modules) but...
Re: Changing to Lowercase Except the First Letter
by InfiniteSilence (Curate) on Jan 30, 2001 at 20:19 UTC
    This appears to work as well:

    #!/usr/bin/perl -w use diagnostics; $s = q(THE DOGGIE FELL OVER); $s =~ s/\b(\w)(\w+)\b/uc($1) . lc($2)/eog; print $s; 1;

    Celebrate Intellectual Diversity