← Back to Archives

Converting strings to titlecase in perl

berkeley

There 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; }