« AB 369 in California | The purrrrrrrfect bird... » |
Converting strings to titlecase in perl
hacks, open sourceThere doesn't seem to be a function in perl for taking a string and returning the string in titlecase (titlecase is where the first letter of each word is capitalized).
So, I wrote one. You should be able to drop this subroutine into any perl program. You would use it like this:
$upper_string = titlecase($lower_string);
Here's the code:
sub titlecase {
#assumes lowercase, space-separated string
#returns same with first letters of words in caps
#use local variables
my ($s) = @_;
my (@st);
#split string
@st = split(/ /, $s);
#loop over strings
$n = 0;
foreach $l (@st) {
#return with first let. caps
$l = ucfirst($l);
#assign back to array
$st[$n] = $l;
$n++;
}
#join the strings into one
$s = join(" ", @st);
return $s;
}
UPDATE [2008-08-14T09:03:59]: Daniel Hyde writes in and points out that this can be performed with a very simple regex:
Comments are disabled, but thought you might be interested to know you can do this with a short sweet regexp too:
s/\b(\w)/\u$1/g;
def titlecase(string):
return ' '.join(word.capitalize() for word in string.split())