CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Converting Lc To Ucfirst

 



perlkid
stranger

Oct 10, 2000, 8:21 PM

Post #1 of 4 (402 views)
Converting Lc To Ucfirst Can't Post

 
How can I take a $scalar stored with a sentence, and convert each word in the sencence to the word with the first letter capitalized.

I though that if I could store (\w+) the same way I could store (.*) then I could do

$scalar =~ s!(\w+)!ucfirst($2)!g;

Oh yea, and why does ucfirst() not actually operate as code, but as text.

In a sentence

this is a test

i would get

ucfirst(this) ucfirst(is) ucfirst(a) ucfirst(test)

why?

But I can't even get that. I can get the first 3 by using

$scalar =~ s!(.*?) !ucfirst($1) !g;

still not what I'm aiming for though.

perlkid


japhy
Enthusiast

Oct 10, 2000, 8:25 PM

Post #2 of 4 (402 views)
Re: Converting Lc To Ucfirst [In reply to] Can't Post

Re-read the perlre documentation. To get the RHS of a s/// to be evaluated as Perl code, you need to use the 'e' modifier to the s///:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


$string =~ s/(\w+)/ucfirst(lc($1))/eg;
</pre><HR></BLOCKQUOTE>

But you can avoid the /e by using the \u and \L escapes sequences:

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>


$string =~ s/(\w+)/\u\L$1/g;
</pre><HR></BLOCKQUOTE>

------------------
Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher



japhy
Enthusiast

Oct 10, 2000, 8:28 PM

Post #3 of 4 (402 views)
Re: Converting Lc To Ucfirst [In reply to] Can't Post

This is even in the FAQ. Perl FAQ 4, "How do I capitalize all the words on one line?"

Excerpt:

To force each word to be lower case, with the first letter upper case:

$line =~ s/(\w+)/\u\L$1/g;


------------------
Jeff "japhy" Pinyan -- accomplished author, consultant, hacker, and teacher



perlkid
stranger

Oct 10, 2000, 9:29 PM

Post #4 of 4 (402 views)
Re: Converting Lc To Ucfirst [In reply to] Can't Post

 
Lol,

I'm sorry,

I should have checked at the FAQ first.

Well, it just makes it more of a frequently asked question. Smile

Thanks Japhy,

Learned a lot,

perlkid

P.S. That made my day. I'm going to play with (\w) and $1 in the mourning. Smile

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives