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

Dear Perl Monks,

Given a string $sentence, how could I

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.