SirBones has asked for the wisdom of the Perl Monks concerning the following question:
Hey wise-guys/gals... :-). Kind of a two part question, the first fine-tuning, is-there-a-better-slicker-Perl-idiom. The second is a request for some split/join guidance.
I've got a list of names that I need to "normalize" according to the following rules:
SMITH, JOHN H. --becomes--> Smith, John H.
Smith, John H. (JOHNNY) --becomes--> Smith, John H. (Johnny)
SMITH, JOHN H. (JOHNNY) *CONTRACTOR* --becomes--> Smith, John H. (John +ny) *CONTRACTOR*
I'm promised (I think) that the items will always be space-separated, although I'm a bit nervous about that one. I think I need to allow for that, just in case. In any event, the following code seems to work if I assume just space delimiters:
#!/usr/bin/perl use strict; use warnings; my @names = ("Foonman, Joseph S. (Joe)", "SMITH, EDWARD", "Perl, Paul M. *CONTRACTOR*", "Jones, Bobby R.", "Ruth, BABE B. *CONTRACTOR*", "CLAUSE, SANTINO (SANTA)", ); for my $n (@names) { print join(" ", map( { if (/^\*/) { $_; } elsif (/^\(/) { "\(".ucfirst(lc(substr($_,1))); } else { ucfirst(lc($_)); } } split(/ /,$n)))."\n"; }
Gives me exactly what I want:
Foonman, Joseph S. (Joe) Smith, Edward Perl, Paul M. *CONTRACTOR* Jones, Bobby R. Ruth, Babe B. *CONTRACTOR* Clause, Santino (Santa)
Part of my learning process with Perl has been to always ask "Is there a better way?" Any ideas? I'd be particularly interested in people pointing out any weaknesses with this approach, and if there is a more concise way to do it.
And back to question 2: Of course this code doesn't work for Claus,Santa (no space delimeter). I'd appreciate any suggestions for handling the case if someone surprises me with only a comma delimeter. I tried splitting on / |,/ but of course that eliminates all the commas in the output. I'm having difficulty since if I'm splitting on either a space or a comma, I don't know how to tell which one forced the split so that I can use the appropriate character when I re-join the whole thing. I hope that makes sense.
Cheers,
Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Splitting/joining on different characters
by japhy (Canon) on May 25, 2006 at 18:39 UTC | |
|
Re: Splitting/joining on different characters
by idsfa (Vicar) on May 25, 2006 at 18:48 UTC | |
by SirBones (Friar) on May 25, 2006 at 19:02 UTC | |
by bpphillips (Friar) on May 25, 2006 at 19:37 UTC | |
by swampyankee (Parson) on May 25, 2006 at 19:22 UTC | |
by SirBones (Friar) on May 25, 2006 at 19:36 UTC | |
|
Re: Splitting/joining on different characters
by dragonchild (Archbishop) on May 25, 2006 at 18:36 UTC | |
|
Re: Splitting/joining on different characters
by dsheroh (Monsignor) on May 25, 2006 at 18:46 UTC |