http://www.perlmonks.org?node_id=857159


in reply to Reversing string case

Following code will help you.

use strict; use warnings; print "Enter the string:"; my $string=<STDIN>; #getting the input from user chomp($string); #remove the newline at end in string if($string=~/^[a-z]+$/) { #checking whether the string is in lowercase print "String given in Lower Case:$string\n"; $string=~s/([a-z])/\u$1/g; #replacing the string to be in upper case print "Uppercase String:$string\n"; } elsif($string=~/^[A-Z]+$/) { #checking whether the string is in upperc +ase print "String given in Upper Case:$string\n"; $string=~s/([A-Z])/\l$1/g; #replacing the string to be in lower case print "Lowercase String:$string\n"; } elsif($string=~/^[a-zA-Z]+$/) { #checking whether the string is in mix +ed case print "String given in Mixed Case:$string\n"; $string=~s/([a-z])/\u$1/g; #replacing the string to be in upper case print "Uppercase String:$string\n"; $string=~s/([A-Z])/\l$1/g; #replacing the string to be in lower case print "Lowercase String:$string\n"; }

Replies are listed 'Best First'.
Re^2: Reversing string case
by Anonymous Monk on Aug 25, 2010 at 12:19 UTC

    Your mixed case test will not work the way you intended

    /[a-zA-Z]/ matches any lower- or uppercase character, not a lower- and then an uppercase one.

    And your two substitutions will not flip the case of a character because after the first substitution (i.e. s/([a-z])/\u$1/g) all characters are uppercase and will be changed to lowercase at the second substitution.