0

I have a string containing all uppercase words and I want to make only the first letter of each word uppercase or convert all but the first character to lowercase. I've been messing around with regex for a while and can't get it right.

NGittlen
  • 319
  • 4
  • 17
  • 1
    Does it need to use regex? If not: http://stackoverflow.com/questions/77226/how-can-i-capitalize-the-first-letter-of-each-word-in-a-string-in-perl\ – OnlineCop Nov 13 '14 at 21:13
  • @OnlineCop The second answer to that question shows how to do this with a regex. This is a duplicate question. – ThisSuitIsBlackNot Nov 13 '14 at 21:19

2 Answers2

5
my $str = "FOOBAR FOOBAR";
$str =~ s/(\S+)/\u\L$1/g;
print $str;

output

Foobar Foobar

Check ucfirst and lc in perldoc.

mpapec
  • 50,217
  • 8
  • 67
  • 127
5

This is a perfect job for ucfirst(), no need regex here :

$ echo 'FOO   BAR BASE' |
    perl -nE '$_ = lc($_); say join " ", map { ucfirst $_ } split /\s/' 

Output:

Foo   Bar Base
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223