Ïðèãëàøàåì ïîñåòèòü
×óêîâñêèé (chukovskiy.lit-info.ru)

Transliteration, Not Substitution

Previous Table of Contents Next

Transliteration, Not Substitution

For this next operator, the transliteration operator (sometimes called the translation operator), think back to how regular expression substitutions work: The substitution operator, which looks like s/pattern/replacement/ and was discussed in Hour 6, works against the $_ variable unless another scalar is specified with a binding operator =~. The transliteration operator works something like that, except that it doesn't use regular expressions and works completely differently. Still follow? The syntax for the transliteration operator is as follows:


tr/searchlist/replacementlist/


The transliteration operator—TR///—searches a string for the elements in searchlist and replaces them with the corresponding elements in replacementlist. By default, the transliteration operator searches and modifies the variable $_. To search and modify other variables, you use a binding operator as you would for regular expression matches, as shown here:


tr/ABC/XYZ/;         # In $_, replaces all A's with X's, B's with Y's, etc..

$r=~tr/ABC/XYZ/;      # Does the same, but with $r


Logical groups of characters are accepted with dashes between them. For example, A-Z represents the capital letters A tHRough Z, so that you don't have to write them all out, as in this example:


tr/A-Z/a-z/;              # Change all uppercase to lowercase

tr/A-Za-z/a-zA-Z/;        # Invert upper and lowercase


If replacementlist is empty or identical to searchlist, the characters matched are counted by tr/// and returned. The target string is not modified, as in the following example:


$eyes=$potato=~tr/i//;      # Count the i's in $potato, return to $eyes

$nums=tr/0-9//;             # Count digits in $_, return to $nums


Finally, for historical reasons, TR/// can also be written as y/// with the same results, because y is a synonym for tr. The TR/// operator (and hence, y///) also allows you to specify an alternate set of delimiters for searchlist and replacementlist. They can be any naturally paired set such as parentheses or any other character, as you can see here:


tr(a-z)(n-za-m);         # Rotate all characters 13 to the left in $_

y[,._-][;:=|];           # Switch around some punctuation


By the Way

The TR/// operator actually has additional functionality, but it isn't used often. To read about all the other tasks TR/// can perform, look at the online documentation in the perlop section.


    Previous Table of Contents Next