From: PerlFAQ Server on
This is an excerpt from the latest version perlfaq4.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at .


4.30: How do I capitalize all the words on one line?

(contributed by brian d foy)

Damian Conway's Text::Autoformat handles all of the thinking for you.

use Text::Autoformat;
my $x = "Dr. Strangelove or: How I Learned to Stop ".
"Worrying and Love the Bomb";

print $x, "\n";
for my $style (qw( sentence title highlight )) {
print autoformat($x, { case => $style }), "\n";

How do you want to capitalize those words?

FRED AND BARNEY'S LODGE # all uppercase
Fred And Barney's Lodge # title case
Fred and Barney's Lodge # highlight case

It's not as easy a problem as it looks. How many words do you think are
in there? Wait for it... wait for it.... If you answered 5 you're right.
Perl words are groups of "\w+", but that's not what you want to
capitalize. How is Perl supposed to know not to capitalize that "s"
after the apostrophe? You could try a regular expression:

$string =~ s/ (
(^\w) #at the beginning of the line
| # or
(\s\w) #preceded by whitespace

$string =~ s/([\w']+)/\u\L$1/g;

Now, what if you don't want to capitalize that "and"? Just use
Text::Autoformat and get on with the next problem. :)


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in