Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Capitalize first letter in a string?

by gorenfeld (Initiate)
on Nov 04, 2000 at 22:47 UTC ( [id://40012]=perlquestion: print w/replies, xml ) Need Help??

gorenfeld has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perl Monks,

Given a string $sentence, how could I

  • 1. Check to see if the first letter (of $sentence, not of every word) is lowercase.
  • 2. Make it uppercase if it's not.

Sincerely,

John Gorenfeld

Replies are listed 'Best First'.
(ar0n) Re: Capitalize first letter in a string?
by ar0n (Priest) on Nov 04, 2000 at 22:58 UTC
    my $string_one = "foo bar baz"; my $string_two = "Foo bar baz"; ucfirst $string_one; lcfirst $string_two; print 'First letter is lowercase in $string_one' if $string_one =~ /^[ +a-z]/; print 'First letter is lowercase in $string_two' if $string_two =~ /^[ +a-z]/;
    (prints 'First letter is lowercase in $string_two')

    See the docs on uc, lc, ucfirst and lcfirst.

    [ar0n]

Re: Capitalize first letter in a string?
by tune (Curate) on Nov 04, 2000 at 23:09 UTC
    And that's not the only way! :-) You can use some regexp too.
    $a = 'haha'; $a =~ s/^([a-z])/\U$1/; print $a;

    -- tune

      Damn straight it's not the only way!! We code Perl goddamit!!. There is Always more than one way of doing it. :)

      --
      
      Brother Frankus.
Re: Capitalize first letter in a string?
by autark (Friar) on Nov 04, 2000 at 23:03 UTC
    You can use the ucfirst function to do this. Assuming you want to uppercase the first character in a string:
    $string = "to my beloved wife"; $string = ucfirst $string; print $string;
    This will print "To my beloved wife". You shouldn't have to test for lowercase as ucfirst will not mangle any characters already in uppercase.

    Autark.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2024-04-18 11:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found