Title case names in perl
Posted: 17 June 2008
While I was at work today I came across a script I wrote a couple of years ago to title case names in perl. This script will transform names to a nice, readable title case equivalent. E.g. "JOHN SMITH" to "John Smith", "JOHN O'BRIAN" to "John O'Brian" and "JOHN MCCOOL" to "John McCool" etc.
#!/usr/bin/env perl
use strict;
sub title_case_name {
my $person = shift;
my ($word, $subWord);
$person =~ s/\s+/ /g;
$person =~ s/^\s+//;
$person =~ s/\s+$//;
my @namesArray = split(/ /, $person);
$person = '';
foreach $word (@namesArray){
$word = title_case($word);
if($word =~ /-/){
my @subWordsArray = split(/-/, $word);
$word = '';
foreach $subWord (@subWordsArray){
$subWord = title_case($subWord);
$word .= $subWord.'-';
}
chop($word);
}
$person .= $word.' ';
}
chop($person);
return $person;
}
sub title_case {
my $name = shift;
my $temp_str1 = '';
my $temp_str2 = '';
$name = lc($name);
$name = ucfirst($name);
$temp_str1 = substr($name, 0, 2);
$temp_str2 = substr($name, 2);
if($temp_str1 eq 'Mc' || $temp_str1 eq "O'") {
$temp_str2 = ucfirst($temp_str2);
$name = $temp_str1 . $temp_str2;
}
return $name;
}
print title_case_name('JOHN SMITH') . "\n";
print title_case_name('JOHN O\'BRIAN') . "\n";
print title_case_name('JOHN MCCOOL') . "\n";Post a comment
Comment Guidelines
- Have no more than 2 links, otherwise your comment will be flagged as spam.
- Links are automagically generated.
- <em>text</em> to make text italic.
- <strong>text</strong> to make text bold.
JavaScript needs to be enabled to comment.
Your comments
No comments have been made. Why not be the first?!