regexperl

Change first character on a line with upper case in Perl


I was trying to change just the first lower case letter of a line from a .txt file to an upper case, using the following

$_ =~ s/^[a-z]/\U/;

What happens, when I execute it, is that instead of changing the lower case to upper case the lower case at the beginning of the line is substituted with the most significant bit on the line. For example, the line nAkld987aBALPaapofikU88 instead of being substituted with NAkld987 becomes Akld987... Perl


Solution

  • You need to capture the first character in a capturing group, and use a back reference to convert it to uppercase using \u.

    Try using this:

    $_ =~ s/^([a-z])/\u$1/;