Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Title Case

Status
Not open for further replies.

columb

IS-IT--Management
Feb 5, 2004
1,231
0
0
EU
I have a cript which creates Unix users. The problem is that the source data can be in any state and I want to change the gecos (real name) to title case. i.e. whether the input is FRED BLOGS, fred blogs or Fred Blogs it should end up as Fred Blogs

So far I've got
Code:
  my @bits;
  foreach ( split / /, $gecos )
    { push @bits, ucfirst ( lc ( $_ ) ); }
  $gecos =  join ' ', @bits;
  print "$gecos\n";
which works but it's not very pretty and there must be a better way using regex. Sommething along the line of
Code:
$gecos = lc $gecos;
$gecos =~ s/\s(\w)/uc($1)/g;
but that doesn't do what I thought it would (and, of course, misses out the first name) Any pointers please?

Ceci n'est pas une signature
Columb Healy
 
Cracked it - it's amazing how posting on TecTips stimulates the brain!
The answer is
Code:
$gecos =~ s/(\w+)/ucfirst(lc($1))/ge;

Ceci n'est pas une signature
Columb Healy
 
Neat solution, Columb. But with all such mechanised solutions, there are always people whose names don't fit the pattern. McLean, O'Brien, de Cozar, etc. etc. [smile]

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
You're right steve, although it does actually correctly handle "O'Brien".
 
Thanks for the tip Steve
Because the office I'm working for is in Glasgow I've amended it to
Code:
$gecos =~ s/(\w+)/ucfirst(lc($1))/ge;
$gecos =~ s/\bMc(\w)/"Mc". uc ($1)/e;
$gecos =~ s/\bMac(\w)/"Mac". uc ($1)/e;
As ishnid says, the 'O'Brians' will work and we don't get too many 'de Cozars'

Ceci n'est pas une signature
Columb Healy
 
Yes, I suppose you are bound to have a higher than normal proportion of Mc... and Mac... in Glasgow!

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
If you're just trying to apply name casing, I suggest that you use the cpan module: NameCase.

- Miller
 
Wow, Miller, just when I'd got it working! The lesson here is search CPAN first.

Ceci n'est pas une signature
Columb Healy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top