Lesson 10 | Perl translation operator |
Objective | Examine the translation operator. |
Perl Translation Operator
The translation operator translates all occurrences of the characters found in the left-hand string with the corresponding characters found in the right-hand string.
For example, if you wanted to translate all numeric characters into asterisks, you could use this:
tr/0-9/*/;
Or, if you wanted to translate all uppercase letters to lowercase:
tr/A-Z/a-z/;
The translations are done on a character-by-character basis, so this operator is useful only for one-to-one translations.
Now that we have covered the three pattern-matching operators, we are ready to start working with them.
The Translation Operator (tr///)
The translation operator (tr///) is used to change individual characters in the $_ variable. It requires two operands, like this:
tr/a/z/;
This statement translates all occurrences of a into z. If you specify more than one character in the match character list, you can translate multiple characters at a time.
For instance:
tr/ab/z/;
translates all a and all b characters into the z character. If the replacement list of characters is shorter than the target list of characters, the last character in the replacement list is repeated as often as
needed. However, if more than one replacement character is given for a matched character, only the first is used.
For instance:
tr/WWW/ABC/;
results in all W characters being converted to an A character. The rest of the replacement list is ignored.
Unlike the matching and substitution operators, the translation operator doesn't perform variable interpolation.
Note The tr operator gets its name from the UNIX tr utility. If you are familiar with the tr utility, then you already know how to use the tr operator. The UNIX sed utility uses a y to indicate translations. To make learning Perl easier for sed users, y is supported as a synonym for tr.