Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Capitalize the first letter of each word

by Adrade (Pilgrim)
on Jul 11, 2005 at 18:18 UTC ( #474045=note: print w/replies, xml ) Need Help??


in reply to Capitalize the first letter of each word

Before I knew about ucfirst(), I wrote the following function to satisfy a specific need - you can use it as the basis for one of your own construction. It doesn't work like ucfirst though, as I needed to catch things like Mr. and Mrs. and have words one or two letters long left in their case... but you get the idea.

sub reform { my $line = shift; my @toret; foreach my $word (split(/\b/,$line)) { if (lc($word) eq 'mrs') { $word = "Mrs."; } elsif (length($word) > 2) { $word =~ s/^(.)(.*)/uc($1).lc($2)/se; } elsif (lc($word) eq 'mr') { $word = "Mr."; } push (@toret, $word); } return join("",@toret); }

adrade@antigone:~$ perl -e 'print ucfirst("il"),"\n"' Il adrade@antigone:~$ perl -e 'print ucfirst("HELLO"),"\n"' HELLO adrade@antigone:~$ perl -e 'print ucfirst("mrs"),"\n"' Mrs # I put reform() in ref.pm adrade@antigone:~$ perl -e 'use ref; print reform("il"),"\n"' il adrade@antigone:~$ perl -e 'use ref; print reform("HELLO"),"\n"' Hello adrade@antigone:~$ perl -e 'use ref; print reform("Mrs"),"\n"' Mrs.
  -Adam

--
By a scallop's forelocks!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://474045]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2023-02-02 15:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (19 votes). Check out past polls.

    Notices?