TheBlackCorsair
TheBlackCorsair

Reputation: 527

Change first character on a line with upper case perl

This is a simple question I guess, but 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...

Upvotes: 26

Views: 23450

Answers (4)

felwithe
felwithe

Reputation: 2744

Being less proficient with regular expressions, I accomplished this with map (which is basically foreach, except it both iterates a list and returns the manipulated list):

$string = join " ", map { ucfirst } split " ", $string;

Upvotes: 0

codaddict
codaddict

Reputation: 455020

You can just use the ucfirst function.

If you want to use regex you can do:

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

or

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

Upvotes: 15

Rohit Jain
Rohit Jain

Reputation: 213233

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

Try using this: -

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

Upvotes: 24

RC.
RC.

Reputation: 28207

You could/should use ucfirst. I say should as it's much more obvious to a maintainer that your intent is to uppercase the first letter of the string. I love a regex, but in this case I feel it's not the correct approach.

my $str = "test";
print ucfirst($str);

Upvotes: 31

Related Questions