Capitalise first letter of each word

Perl provides uc(), lc() and ucfirst() to translate a string to uppercase, lowercase and to capitalise the first letter of the string, but doesn't provide a convenient method to uppercase the first letter of each word of a string.

This is most often needed for names, for example “david precious”, “David precious” and “DAVID PRECIOUS” should generally be changed to “David Precious” when pretty-printing.

The following code snippet will do exactly that:

$name = join ' ', map { ucfirst $_ } split /\s/, lc $name;

Turn it into a sub if you're going to use it often, it's not immediately obvious what it does.

UPDATE: of course the code above doesn't handle double-barrelled names (eg “Dave Two-Names”) nor names like Johnny McScottish or Old MacDonald.

This regexp version will deal with those:

$name = lc $name;
$name =~ s/(^|\W)(\w)/\1\u\2/g;
# fix any "McSomething" names:
$name =~ s/(Ma?c)([a-z])/\1\u\2/g;

Other features which would be nice to add include the ability to uppercase abbreviations like CBE, MBE that pompous people may have included.

perl/capitalisewords.txt · Last modified: 2010/02/26 10:45 (external edit)
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki