Perl, using tr function to convert uppercase to lowercase and vice-versa at the same time?

Brian picture Brian · Apr 9, 2011 · Viewed 30.1k times · Source

I have a string

$string= 'AbCdEf';

and I want to use the tr function to convert all the uppercase letters to lower case and all the lower case to upper case.... at the same time. I basically just want to reverse it to become.

aBcDeF

I came up with this line, but I'm not sure how to modify it to do what I want. Any help please?

$string=~ tr/A-Z/a-z/;

Thanks!

Answer

hobbs picture hobbs · Apr 9, 2011

At Tom's request, the Unicode-clean (or locales-clean) version:

s/([[:upper:]])|([[:lower:]])/defined $1 ? lc $1 : uc $2/eg