Neil Ang

Bersonal Plog

A stunning likeness of Neil Ang
Super Nerd

Title case names in perl

Posted on .

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";