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

Hi there Monks!
I am trying to capitalize only the first letter on the first word in a string but I can not get this code to work:
my $city_state = “ BELLMONT NY”; $city_state = join '', map { ucfirst $city_state } split /\s+/ || '' +; # Bellmont NY
I wonder what to do if this would happen:
my $city_state = “ NEW YORK NY”; $city_state = join '', map { ucfirst $city_state } split /\s+/ || '' +; # New York NY
Any suggestions or a better more efficient way of doing it?
Thanks for looking!

Replies are listed 'Best First'.
Re: Capitalize only the first letter of the first word in a string
by toolic (Bishop) on Feb 03, 2015 at 20:05 UTC
    You need lc also:
    use warnings; use strict; while (<DATA>) { s/(\w+)/ucfirst lc $1/e; print; } __DATA__ BELLMONT NY NEW YORK NY

    outputs:

    Bellmont NY New YORK NY
Re: Capitalize only the first letter of the first word in a string
by GrandFather (Saint) on Feb 03, 2015 at 20:05 UTC

    ucfirst upper cases the first letter and leaves the remaining letters unchanged so you need to lowercase the string first. That will give you the answer you claim to want, but not the result you indicate in your code. For that you need something more like:

    use strict; use warnings; for my $str ('BELLMONT NY', 'NEW YORK NY') { my @words = split /\s+/, $str; $_ = ucfirst lc for grep {/\w{3,}/} @words; print "$str: ", join (' ', @words), "\n"; }

    Prints:

    BELLMONT NY: Bellmont NY NEW YORK NY: New York NY
    Perl is the programming world's equivalent of English
Re: Capitalize only the first letter of the first word in a string
by AnomalousMonk (Archbishop) on Feb 03, 2015 at 20:28 UTC

    Another way:

    c:\@Work\Perl>perl -wMstrict -le "for my $s (' bElLmOnT NY', ' NeW yOrK NY', ' sAuLt StE. mArIe MI',) { my $t = $s; my $name = qr{ [[:alpha:]]+ [.]? }xms; $t =~ s{ \b ($name) (?= \s+ $name) } {\u\L$1}xmsg; print qq{'$s' -> '$t'}; } " ' bElLmOnT NY' -> ' Bellmont NY' ' NeW yOrK NY' -> ' New York NY' ' sAuLt StE. mArIe MI' -> ' Sault Ste. Marie MI'
    This takes advantage of the fact that a city name or portion thereof looks like a state/provincial zip/postal code abbreviation (but not an ISO one, apparently). See  \u \L and their friends  \U \l \F \Q \E in Quote and Quote-like Operators.


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