Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capitalize the first letter of each word in a string in Perl?

What is the easiest way to capitalize the first letter in each word of a string?

like image 330
Dan Littlejohn Avatar asked Sep 16 '08 21:09

Dan Littlejohn


People also ask

How do I make the first letter capital in Perl?

Perl | uc() Function uc() function in Perl returns the string passed to it after converting it into uppercase. It is similar to ucfirst() function which returns only first character in uppercase.

How do you capitalize every letter in a string?

The upper() method converts all lowercase characters in a string into uppercase characters and returns it.

Which function capitalize the first character of a string?

Convert the First Letter to uppercase You may use toUpperCase() method and convert the calling string to upper case.


2 Answers

As @brian is mentioning in the comments the currently accepted answer by @piCookie is wrong!

$_="what's the wrong answer?"; s/\b(\w)/\U$1/g print;  

This will print "What'S The Wrong Answer?" notice the wrongly capitalized S

As the FAQ says you are probably better off using

s/([\w']+)/\u\L$1/g 

or Text::Autoformat

like image 189
4 revs, 3 users 93% Avatar answered Oct 22 '22 21:10

4 revs, 3 users 93%


See the faq.

I don't believe ucfirst() satisfies the OP's question to capitalize the first letter of each word in a string without splitting the string and joining it later.

like image 35
piCookie Avatar answered Oct 22 '22 20:10

piCookie