Controlling Case
Problem
A string in uppercase needs converting to lowercase, or vice versa.
Solution
Use the lc
and
uc functions or the \L and
\U
string
escapes.
use locale; # needed in 5.004 or above $big = uc($little); # "bo peep" -> "BO PEEP" $little = lc($big); # "JOHN" -> "john" $big = "\U$little"; # "bo peep" -> "BO PEEP" $little = "\L$big"; # "JOHN" -> "john"
To alter just one character, use the lcfirst
and ucfirst functions or the \l
and \u string escapes.
$big = "\u$little"; # "bo" -> "Bo" $little = "\l$big"; # "BoPeep" -> "boPeep"
Discussion
The functions and string escapes look different, but both do the same thing. You can set the case of either the first character or the whole string. You can even do both at once to force uppercase on initial characters and lowercase on the rest.
The use
locale directive tells Perl’s
case-conversion functions and pattern matching engine to respect your
language environment, allowing for characters with diacritical marks,
and so on. A common mistake is to use
tr///
to convert case. (We’re aware that
the old Camel book recommended tr/A-Z/a-z/. In our
defense, that was the only way to do it back then.) This won’t
work in all situations because when you say
tr/A-Z/a-z/ you have omitted all characters with
umlauts, accent marks, cedillas, and other diacritics used in dozens
of languages, including English. The uc and
\U case-changing commands understand these
characters and convert them properly, at least when you’ve said
use
locale
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access