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

Novice perl user here asking for a bit of help. I have a bunch of data that was badly formatted to contain strings like this:

Washington, D.c.

and

New York, N. y.

I'm trying to process the data to correct these instances, ie change 'D.c.' to 'D.C.' etc.

This is what I tried:

$this_term = 'Washington, D.c.'; $this_term =~ s/\.[a-z]/\.[A-Z]/g; print "$this_term";

I get this:

'Washington, D.A-Z.' instead of the desired 'Washington, D.C.'

Can someone show me what I'm doing wrong? I've spent a stupid amount of time on this, and I know the solution must be simple, but I can't find it.

Thanks gang.

Replies are listed 'Best First'.
Re: replacing part of a string with its uppercase via regex
by choroba (Cardinal) on Mar 16, 2014 at 21:44 UTC
    The second part of a substitution is just a plain string, not a regular expression. To include a part from the matched string, you have to use capture groups, introduced by parentheses. To uppercase a part of a string, use \U:
    $this_term =~ s/\.([a-z])/.\U$1/g;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: replacing part of a string with its uppercase via regex
by AnomalousMonk (Archbishop) on Mar 16, 2014 at 21:47 UTC
    c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'Washington, D.c., New York, N.y.'; $s =~ s/(\.[a-z])/\U$1/g; print qq{'$s'}; " 'Washington, D.C., New York, N.Y.'
Re: replacing part of a string with its uppercase via regex (replacing part of a string with its uppercase)
by shmem (Chancellor) on Mar 16, 2014 at 23:40 UTC

    Since exhausting solutions were given, now to formalities... to wit:
    A meaningful title helps others when searching for something.

    People don't search for simple questions, since they've got plenty of them already.
    A better title would have been something like "replacing part of a string with its uppercase via regex".

    No harm meant but information.

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
Re: replacing part of a string with its uppercase via regex
by brewzzer (Novice) on Mar 17, 2014 at 00:20 UTC
    Thanks everybody. Changed title of question as suggested.
      Changed title of question as suggested

      Wonderful!

      Nearly 9 years later, that change enabled Google to find the answer to my question...