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

故事扮演 提交于 2019-11-29 05:27:42
piCookie

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.

Pat

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

Take a look at the ucfirst function.

$line = join " ", map {ucfirst} split " ", $line;
kixx
$capitalized = join '', map { ucfirst lc $_ } split /(\s+)/, $line;

By capturing the whitespace, it is inserted in the list and used to rebuild the original spacing. "ucfirst lc" capitalizes "teXT" to "Text".

$string =~ s/(\w+)/\u$1/g;

should work just fine

alemol

This capitalizes only the first word of each line:

perl -ne "print (ucfirst($1)$2)  if s/^(\w)(.*)/\1\2/" file

Note that the FAQ solution doesn't work if you have words that are in all-caps and you want them to be (only) capitalized instead. You can either make a more complicated regex, or just do a lc on the string before applying the FAQ solution.

vsync

You can use 'Title Case', its a very cool piece of code written in Perl.

RET

The ucfirst function in a map certainly does this, but only in a very rudimentary way. If you want something a bit more sophisticated, have a look at John Gruber's TitleCase script.

bill god

try this :

echo "what's the wrong answer?" |perl -pe 's/^/ /; s/\s(\w+)/ \u$1/g; s/^ //'

What's The Wrong Answer?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!