For a Perl variable,
$name
, which contains a name in the form
first name followed by a space and then the last name with all letters in
uppercase, the following code will change the name so that only the first
letter of both parts of the name is capitalized with the rest of the name
in lowercase. E.g. if $name contains JOHN SMITH
, afterwards it
will contain John Smith
.
# The name is in all uppercase letters. Leave the first letter of
# each part of the name in upper case, but put all the others in lowercase
$name =~ tr/A-Z/a-z/;
$name =~ s/([a-z]+)\s([a-z]+)/\u$1 \u$2/;
The first line changes all uppercase letters to lowercase. The next line looks for the first part of the name, which is stored in $1. There is then a space followed by the last name, which is stored in $2. Using the substitute command, the first letter of $1 is changed to uppercase as is the first letter of $2.
The [a-z]
instructs Perl to look for an occurrence of any
letter from "a" to "z". The +
afterwards indicates that Perl should
look for 1 or more occurrences of any letter between "a" and "z". Enclosing
the [a-z]+
between (
and )
instructs
Perl to store what if finds, i.e. the first name in this case, in a variable
$1
. The \s
tells it to look for a whitespace
character, i.e. a space in this
case, and then the next ([a-z]+)
will find all of the letters for
the last name and store it in a variable $2
The \u
changes the following letter to uppercase for $1
, which is the
first name. The \u$2
then changes the first letter of $2
, which is the last name to uppercase.